# coding:utf-8

import json

from gm_types.gaia import USER_TYPE

from utils.rpc import rpc_client
from utils.protocol import gm_protocol


def get_user_type_by_uid(uid):
    """

    :param uid:
    :return:
    """
    from talos.cache.base import user_type_cache

    k = str(uid)
    res = user_type_cache.get(k)
    if res:
        return json.loads(res)

    result = get_user_type_by_uids([uid])
    if not result:
        return {}

    user_type_cache.set(k, json.dumps(result[str(uid)]))
    user_type_cache.expire(k, 60 * 60 * 24 * 7)

    return result[str(uid)]


def get_user_gm_url(uid):

    gm_url = gm_protocol.get_user_homepage(user_id=uid)

    user_type_info = get_user_type_by_uid(uid)
    if not user_type_info:
        return gm_url

    user_type = user_type_info.get("user_type", USER_TYPE.NORMAL)

    if user_type == USER_TYPE.OFFICER:
        gm_url = gm_protocol.get_hospital_home(hospital_id=user_type_info["hospital_id"])

    elif user_type == USER_TYPE.EXPERT:
        gm_url = gm_protocol.get_expert_home(expert_id=user_type_info["doctor_id"])

    return gm_url


def get_user_type_by_uids(uids):
    """
    :param uids:
    :return:
    """

    res = rpc_client['api/users/user_type'](uids=uids).unwrap()

    return res
