# -*- coding: utf8 -*-

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

from qa.utils.time import get_timestamp_or_none


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, new_version=False):
        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:'

        if not new_version:
            self._vote_key_prefix_format = 'user:{user_id}:votes:received'
        else:
            self._vote_key_prefix_format = 'user:{user_id}:votes:received:v1'

        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 += str(topicvote_id)
        self._cache_this(v)

    def receive_answer_vote(self, answer_id):
        v = self._answer_vote_key_prefix
        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
