#!/usr/bin/env python
# coding=utf-8
from django.contrib.auth.models import User, AnonymousUser

from rpc.tool.error_code import CODES, gen


from api.tool.verification_code import generate_referral_code
from api.models import UserExtra

from hippo.models.doctor import Doctor


def get_user_by_id(user_id):
    try:
        user = User.objects.get(id=user_id)
        return user
    except User.DoesNotExist:
        return None


def get_user_extra_by_user_id(user_id, phone=None):
    extra = None
    if user_id:
        try:
            extra = UserExtra.objects.get(user_id=user_id)
        except UserExtra.DoesNotExist:
            while True:
                referral_code = generate_referral_code(10)
                if UserExtra.objects.filter(referral_code=referral_code).exists():
                    # 如果该邀请码已经存在，则继续
                    continue
                else:
                    # 邀请码不存在，创建新的
                    extra = UserExtra.objects.create(
                        user_id=user_id, referral_code=referral_code, phone=phone)
                    break
    return extra


def get_user_by_doctor_id(doctor_id):
    try:
        doctor = Doctor.objects.get(id=doctor_id)
        return doctor.user
    except Doctor.DoesNotExist:
        return None


def get_doctor_by_user_id(user_id):
    """get doctor by user id."""
    if not user_id:
        return None  # protect ourselves

    try:
        doctor = Doctor.objects.get(user__id=user_id)
        return doctor
    except Doctor.DoesNotExist:
        return None


def get_doctor_from_context(ctx):
    user = ctx.session.user if not isinstance(ctx.session.user, AnonymousUser) else None
    if user:
        return get_doctor_by_user_id(user.id)
    else:
        return None


def get_doctor_from_context_or_exception(ctx):
    d = get_doctor_from_context(ctx)
    return d if d else gen(CODES.DOCTOR_NOT_FOUND)

