import json

from qa.cache import answer_sort_cache
from qa.models import Question, Answer


class AnswerSortCacheManager(object):
    def __init__(self):
        self.cache = answer_sort_cache

    def calc_cache(self, question_id):
        recommand = Question.objects.get(id=question_id).recommend_answer
        ids = list(Answer.objects.filter(question_id=question_id,
                                         is_online=True,
                                         is_recommend=False)
                   .order_by('-like_num', 'id').values_list('id', flat=True))
        if recommand:
            ids = [recommand.id] + ids
        self.cache.setex(str(question_id), 2 * 60, json.dumps(ids))
        return ids

    def get_sort_cache(self, question_id):
        sort_cache = answer_sort_cache.get(str(question_id))
        if sort_cache:
            return json.loads(sort_cache)
        else:
            return self.calc_cache(question_id)
