# encoding=utf-8

from __future__ import unicode_literals

from api.tool.user_tool import get_user_from_context
from api.tool.person import update_password

from api.models import VERIFY_CODE_TYPE, Person
from api.models import validate_password

from rpc.decorators import bind_context, bind
from rpc.tool.error_code import CODES, gen
from rpc.tool.log_tool import logging_exception
from rpc.cache import code_cache
from hippo.models import Doctor


@bind_context("doctor/user/set_password", login_required=True)
def update_doctor_password(ctx, password, code):
    """
     医生修改密码
    """
    user = get_user_from_context(ctx)

    key = "phone:%d:%s:%s" % (VERIFY_CODE_TYPE.UPDATE, user.person.id.hex, user.person.phone)
    verified_code = code_cache.get(key)
    if verified_code is None:
        return gen(CODES.INVALID_CODE)
    else:
        if verified_code == code:
            try:
                update_password(user.person, password)
                user.backend = "django.contrib.auth.backends.ModelBackend"
                ctx.session.do_login(user)
                data = {
                    "session_key": ctx.session.session_key
                }
                return data
            except:
                logging_exception()
                return gen(CODES.UNKNOWN_ERROR)
        else:
            return gen(CODES.INVALID_CODE)


@bind_context("doctor/user/login")
def doctor_login(ctx, phone, password):
    phone = phone.strip()

    try:
        try:
            person = Person.objects.get(phone=phone)
        except Person.DoesNotExist:
            person = Person.objects.get(user__username=phone)
        doctor = Doctor.objects.filter(user=person.user).first()
        if doctor is None:
            return gen(CODES.DOCTOR_NOT_FOUND)
    except Person.DoesNotExist:
        return gen(CODES.PERSON_NOT_FOUND)

    if validate_password(password, person):
        person.user.backend = "django.contrib.auth.backends.ModelBackend"
        ctx.session.do_login(person.user)
        data = person.data(True)
        data["session_key"] = ctx.session.session_key
        data["uid"] = person.user.id
        data["doctor"] = doctor.data()
        if doctor.hospital:
            data["hospital"] = doctor.hospital.data()
        return data
    else:
        return gen(CODES.LOGIN_FAIL)

