# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

import json

from talos.services.base import ServiceBase
from talos.services.base import RpcServiceModelCache
from talos.cache.base import talos_rpc_service_model_cache
from talos.services.models.hospital import Hospital


class HospitalService(ServiceBase):
    _model_name = 'hospital'

    __cached_layer = RpcServiceModelCache(talos_rpc_service_model_cache, _model_name)

    @classmethod
    def _generate_hospital_object_from_rpc_hospital_data(cls, result):
        if not result:
            return None

        hospital = Hospital.from_dict(result)
        return hospital

    @classmethod
    def _cache_hospital(cls, hospital):
        v = hospital.to_json()
        cls.__cached_layer.set(hospital.id, v, 60 * 60)

    @classmethod
    def _get_hospital_from_cache_by_ids(cls, hospital_ids):
        cached_info = cls.__cached_layer.mget(hospital_ids)

        result = []

        missing = cached_info.pop(cls.__cached_layer.missing_k)
        if missing:
            rpc_result = cls.call_rpc('api/hospital/by_ids', ids=missing)
            if rpc_result:
                for info in rpc_result:
                    hospital = Hospital.from_dict(info)
                    if not hospital:
                        continue

                    result.append(hospital)
                    cls._cache_hospital(hospital)

        for k in cached_info:
            i = cached_info[k]
            v = json.loads(i)
            h = Hospital.from_dict(v)
            result.append(h)

        return result

    @classmethod
    def get_hospital_from_hospital_ids(cls, ids):
        return cls._get_hospital_from_cache_by_ids(ids)

    @classmethod
    def get_hospital_from_hospital_id(cls, id):
        if id is None:
            return None

        result = cls.get_hospital_from_hospital_ids(ids=[id, ])
        if len(result) > 0:
            return result[0]
        else:
            return None

    @classmethod
    def get_hospital_from_doctor_id(cls, id):
        if id is None:
            return None
        try:
            result = cls.call_rpc('api/hospital/by_doctor_id', doctor_id=id)
        except Exception:
            return None
        return cls._generate_hospital_object_from_rpc_hospital_data(result)

    @classmethod
    def get_hospital_info_by_hospital_id(cls, hospital_id):
        """get_hospital_from_hospital_id方法返回的数据项在services／models/hospital中定义
            为了不污染model，对涉及model外的数据重新定义方法获取
        """
        try:
            result = cls.call_rpc('api/hospital/info_by_hospital_id', hospital_id=hospital_id)

        except Exception:  # TODO CR 检查是否为相应的RPC Exception
            return {}

        return result
