# coding:utf8
from django.conf import settings
from gm_types.gaia import VERIFY_CODE_TYPE

from api.models import Person
from api.tool.datetime_tool import get_seconds_left_to_end_of_day
from api.tool.verification_code import VerifiedCode
from rpc.cache import email_cache, code_cache
from rpc.decorators import bind
from rpc.tool.error_code import CODES, gen
from rpc.tool.internal_email_tool import send_user_email


@bind('api/email/send_code')
def email_code(email, code_type=VERIFY_CODE_TYPE.CREATE):
    if code_type not in [VERIFY_CODE_TYPE.CREATE,
                         VERIFY_CODE_TYPE.LOGIN,
                         VERIFY_CODE_TYPE.UPDATE_PHONE]:
        return gen(CODES.OPERATION_NOT_SUPPORTED)

    email = email.strip()
    send_times = email_cache.get(email)

    try:
        Person.objects.get(email=email)
        if code_type == VERIFY_CODE_TYPE.CREATE:
            return gen(CODES.PERSON_EXIST)
    except Person.DoesNotExist:
        if code_type == VERIFY_CODE_TYPE.LOGIN:
            return gen(CODES.PERSON_NOT_FOUND)

    if not send_times:
        email_cache.setex(email, get_seconds_left_to_end_of_day(), 0)
        send_times = 0

    if int(send_times) >= settings.EMAIL_SEND_MAX_TIMES:
        gen(CODES.SENT_TOO_MANY_EMAIL)
    else:
        email_cache.incr(email)
        code = VerifiedCode.generate(email, code_type)
        send_user_email(email, u'更美验证码', settings.EMAIL_CONTENT % code,
                        from_addresses=settings.NO_REPLY_EMAIL)
    return gen(CODES.SUCCESS)
