# coding=utf-8

from __future__ import unicode_literals, absolute_import, print_function

import datetime
import json

from gm_types.gaia import DIARY_OPERATION
from .base import diary_heat_score_cache


class DiaryHeatScoreCache(object):
    """
    日记本热度相关信息存储
    """
    LAST_CALCULATED_TIME = 'last_calculated_time:{}'
    PREVIOUS_DAY_TIME = 'previous_day_time:{}'
    ACTION_NUM_MAP = 'action_num_map:{}'

    def set_last_calculated_time(self, diary_id, time):
        t = time.strftime('%Y-%m-%d %H:%M:%S')
        key = self.LAST_CALCULATED_TIME.format(diary_id)
        diary_heat_score_cache.set(key, t)

    def get_last_calculated_time(self, diary_id):
        key = self.LAST_CALCULATED_TIME.format(diary_id)
        t = diary_heat_score_cache.get(key)
        if t is not None:
            time = datetime.datetime.strptime(t, '%Y-%m-%d %H:%M:%S')
        else:
            time = datetime.datetime.now()
            self.set_last_calculated_time(diary_id, time)
        return time

    def set_previous_day_time(self, diary_id, time):
        t = time.strftime('%Y-%m-%d %H:%M:%S')
        key = self.PREVIOUS_DAY_TIME.format(diary_id)
        diary_heat_score_cache.set(key, t)

    def get_previous_day_time(self, diary_id):
        key = self.PREVIOUS_DAY_TIME.format(diary_id)
        t = diary_heat_score_cache.get(key)
        if t is not None:
            time = datetime.datetime.strptime(t, '%Y-%m-%d %H:%M:%S')
        else:
            time = datetime.datetime.now()
            self.set_previous_day_time(diary_id, time)
        return time

    def set_action_num_map(self, diary_id, map):
        s = json.dumps(map)
        key = self.ACTION_NUM_MAP.format(diary_id)
        diary_heat_score_cache.set(key, s)

    def get_action_num_map(self, diary_id):
        key = self.ACTION_NUM_MAP.format(diary_id)
        m = diary_heat_score_cache.get(key)
        if m is not None:
            map = json.loads(m)
        else:
            map = self.reset_action_num_map(diary_id)
        return map

    def reset_action_num_map(self, diary_id):
        map = {
            DIARY_OPERATION.CREATE_TOPIC: 0,
            DIARY_OPERATION.MODIFY_DIARY: 0,
            DIARY_OPERATION.SELF_REPLY:   0,
            DIARY_OPERATION.OTHER_REPLY:  0,
            DIARY_OPERATION.OTHER_VOTE:   0,
            'replied_user_ids':          [],    # 记录发布人回复的用户id
            'devices_reply_num_map':     {},    # 记录每台设备回复的次数
        }
        self.set_action_num_map(diary_id, map)
        return map

diary_heat_cache = DiaryHeatScoreCache()
