#!/usr/bin/env python
# coding=utf-8
import base64


class BaseUnread(object):

    _cache_time = 86400  # 缓存一天

    _time_fmt = '%Y-%m-%d %H:%M:%S'  # 记录用户最新操作时间存储的格式

    def __init__(self, user_id=None, doctor_id=None):
        assert any([user_id, doctor_id])
        self.user_id = None
        self.doctor_id = None

    def _reload_user(self):
        if self.user_id is not None:
            return
        assert self.doctor_id
        from hippo.models import Doctor
        self.user_id = Doctor.objects.get(id=self.doctor_id).user_id

    def gen_cache_key(self, event, *args, **kwargs):
        """
            1. 在用户通用缓存中，使用该方法，需要传递 参数 is_user=True
            2. 子类必须要初始化self.user或者self.doctor
        """
        is_user = kwargs.get('is_user', False)
        if is_user:
            key = u'user:{}:{}'.format(self.user_id, event)
        else:
            key = u'doctor:{}:{}'.format(self.doctor_id, event)
        return key

    def gen_order_viewtime_key(self, pre):
        """
            医生最后一次访问订单列表缓存时间所用的key
        """
        return u'{}:time'.format(pre)

    def gen_conversation_key(self, conversation_id=None):
        """
            私信未读，以hash的方式存储，返回一对值
        """
        name = u'conversation:{}'.format(self.user_id)
        return name, conversation_id


def gen_poll_channel(doctor_id):
    """
        连接poll需要的channel_name
    """
    doctor_id_str = base64.b64encode(doctor_id.encode('utf-8'))
    return u"gaia:doctor:unread:{}".format(doctor_id_str)


def gen_poll_named_channel(user_id):
    """生成连接poll需要的channel_name

    :param user_id: 用户ID
    :rtype: unicode
    """
    userid_base64 = base64.b64encode(user_id.encode('utf-8'))
    return u"poll_channel:{}".format(userid_base64)
