# -*- coding: utf-8 -*-
from random import randint

from django.conf import settings
from django.core.mail import send_mail, EmailMessage, EmailMultiAlternatives
import json
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from order_contract.email.email_custom import EmailMultiAlternativesWithEncoding
from order_contract.models import *

#function of Password certification
@csrf_exempt
def passSendMail(request):
    order_id = request.POST.get('order_id')
    email_to = request.POST.getlist('email[]')


    order = OrderContract.objects.get(id=order_id)
    email_to.append(order.kindergarten.user_profile.user.email)
    if order.authentication_code:
        authentication_code = order.authentication_code
    else:
        authentication_code = randint(100000, 999999)
        order.authentication_code = authentication_code
        order.save()

    subject = '[스마트학생복이 만든 리틀스마트] 공급 계약 체결의 件'
    message = '\n안녕하세요. \n ' \
              '스마트학생복이 만든 리틀스마트 입니다. \n ' \
              '아이들이 입는 옷인 만큼 안정성을 최우선 하는 \n ' \
              '아이를 키우는 원복 “리틀스마트”를 선택 해주셔서 감사합니다. \n \n ' \
              '사이즈 추천 시스템 (학부모님용) : http://'+ str(request.get_host()) +'/measurement/size_recommend/intro/' + str(order_id) + ' \n \n ' \
              '사이즈 제출 현황  (유치원용) : http://'+ str(request.get_host()) +'/measurement/stats/submission/guest/' + str(order_id) + ' \n \n ' \
              '인증코드 : '+str(authentication_code)+'  (사이즈추천시스템,사이즈 현황 인증코드 입니다. 등록 필수 사항)'

    # mail = EmailMessage(
    #     subject,
    #     message,
    #     settings.EMAIL_HOST_USER + '@s-fd.com',
    #     email_to,
    #     [order.kindergarten.user_profile.user.email, settings.EMAIL_HOST_USER + '@s-fd.com']
    # )
    # mail.attach_file(order.estimate_pdf.path)
    # mail.attach_file(order.contract_pdf.path)
    # mail.attach_file(order.pamphlet_pdf.path)
    # mail.encoding = 'utf-8'
    # mail.send()

    kwargs = dict(
        to=email_to,
        from_email=settings.EMAIL_HOST_USER + '@s-fd.com',
        subject=subject,
        body=message,
        bcc=['little-smart@s-fd.com']
    )
    # message = EmailEncodeUTF8(**kwargs)
    message = EmailMultiAlternativesWithEncoding(**kwargs)
    message.attach_file(order.estimate_pdf.path)
    message.attach_file(order.contract_pdf.path)
    message.attach_file(order.pamphlet_pdf.path)
    message.send()

    variables = {'success':True}
    return HttpResponse(json.dumps(variables), content_type="application/json")