# -*- coding: utf8 -*-

from gm_types.gaia import VOTEOBJECT
from django.utils import timezone

from api.tool.datetime_tool import get_timestamp_or_none
from rpc.context import get_gaia_local_invoker,get_rpc_remote_invoker
from rpc.tool.log_tool import logging_exception


class VoteTool(object):
    """vote tool for user.

    add vote info into ssdb, if user's topic/diary received new vote.
    """

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

        self._diary_vote_key_prefix = 'd:'
        self._topic_vote_key_prefix = 't:'
        self._answer_vote_key_prefix = 'a:'
        self._vote_key_prefix_format = 'user:{user_id}:votes:received'

        self._k = self._vote_key_prefix_format.format(user_id=user_id)

    def _cache_this(self, k):
        now = timezone.now()
        score = get_timestamp_or_none(now)
        self.redis_c.zadd(self._k, score, k)

    def receive_diary_vote(self, diaryvote_id):
        v = self._diary_vote_key_prefix
        v = v + str(diaryvote_id)
        self._cache_this(v)

    def receive_topic_vote(self, topicvote_id):
        v = self._topic_vote_key_prefix
        v = v + str(topicvote_id)
        self._cache_this(v)

    def receive_answer_vote(self, answer_id):
        v = self._answer_vote_key_prefix
        v = v + str(answer_id)
        self._cache_this(v)

    def get_votes_received(self, start_num=0, count=10):
        """return list of tuple as [(id, type), ]"""
        result = self.redis_c.zrevrange(self._k, start_num, start_num + count - 1)
        if not result:
            return []

        res = []
        for r in result:
            t, v = r.split(':')
            t += ':'  # hmmm,,,
            if t == self._diary_vote_key_prefix:
                res.append((v, VOTEOBJECT.DIARY))

            elif t == self._topic_vote_key_prefix:
                res.append((v, VOTEOBJECT.TOPIC))

            elif t == self._answer_vote_key_prefix:
                res.append((v, VOTEOBJECT.ANSWER))
        return res

    def get_vote_count(self):
        return self.redis_c.zcard(self._k)


def get_user_unread_vote_count():
    try:
        rpc_invoker = get_gaia_local_invoker()
        topic_vote = rpc_invoker['topic/unread_votes_count']().unwrap()
        rpc_mimas = get_rpc_remote_invoker()
        answer_vote = rpc_mimas['qa/answervote/get_unread_count']().unwrap()
        result = topic_vote + answer_vote
        return result
    except:
        logging_exception()
        return 0


def get_answer_vote_info_by_ids(vote_ids):
    try:
        rpc_invoker = get_rpc_remote_invoker()
        vote_info = rpc_invoker['qa/answervote/get_info_by_ids'](vote_ids=vote_ids).unwrap()
        return vote_info
    except:
        logging_exception()
        return False


def get_answer_vote_info_by_id(vote_id):
    vote_info = get_answer_vote_info_by_ids([vote_id])
    return vote_info.get(str(vote_id))
