#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.utils import timezone
from talos.libs.datetime_utils import get_timestamp_or_none
from talos.cache.base import tractate_reply_cache


class ReplyTool(object):

    def __init__(self, redis_c, user_id):
        self.user_id = user_id
        self.redis_c = redis_c

        self.user_tractate = '{user_id}_{tractate_id}'
        self._k = '{user_id}_tractate'.format(user_id=user_id)
        self.doctor_article = '{user_id}_d_{tractate_id}'
        self.doctor_k = '{user_id}_article'.format(user_id=user_id)

    def update_tractate_time(self, tractate_id):
        now = timezone.now()
        score = get_timestamp_or_none(now)
        self.redis_c.zadd(self._k, score, tractate_id)

    def update_tractate_reply(self, tractate_id, reply_id):
        temp_str = self.user_tractate.format(user_id=self.user_id, tractate_id=tractate_id)
        self.redis_c.set(temp_str, reply_id)

    def get_tractate_id(self, start_num=0, count=10):
        result = self.redis_c.zrevrange(self._k, start_num, start_num + count)
        if not result:
            return []

        result = [int(key) for key in result]
        return result

    def get_reply_ids(self, traceate_ids):
        reply_ids, dic_reply = [], {}
        for traceate_id in traceate_ids:
            temp_key = self.user_tractate.format(user_id=self.user_id, tractate_id=traceate_id)
            reply_ids.append(self.redis_c.get(temp_key))
            dic_reply[traceate_id] = int(self.redis_c.get(temp_key))
        return reply_ids, dic_reply


def reply_update_cache(user_id, tractate_id, reply_id):
    reply_pool = ReplyTool(redis_c=tractate_reply_cache, user_id=user_id)

    reply_pool.update_tractate_time(tractate_id=tractate_id)
    reply_pool.update_tractate_reply(tractate_id=tractate_id, reply_id=reply_id)


def get_reply_ids(user_id, offset=0, count=10):
    reply_pool = ReplyTool(redis_c=tractate_reply_cache, user_id=user_id)

    tractate_ids = reply_pool.get_tractate_id(start_num=offset, count=count)
    reply_ids, dic_reply = reply_pool.get_reply_ids(traceate_ids=tractate_ids)

    return {
        "tractate_ids": tractate_ids,
        "reply_ids": reply_ids,
        "dic_reply": dic_reply,
    }