import logging
import json

from rpc.cache import search_dic_cache
from ..models.search import WordsRecomend

logger = logging.getLogger(__name__)


class WordsCache(object):
    def __init__(self):
        self.cache = search_dic_cache

    def get_key(self, tab_type, province_id):
        return str(tab_type) + ':' + str(province_id)

    def update_cache(self, tab_type, province_id):
        v = []
        try:
            words = WordsRecomend.objects.get(tab=tab_type, province_id=province_id).words
            if words:
                key = self.get_key(tab_type, province_id)
                self.cache.set(key, words, ex=60 * 60 * 6)
                v = json.loads(words)
                return v

        except WordsRecomend.DoesNotExist:
            logger.warning('cannot get recommend words from db, tab type is {} and province id is {}'.format(tab_type,
                                                                                                             province_id))

        return v

    def get_words(self, tab_type, province_id):
        key = self.get_key(tab_type, province_id)
        v = self.cache.get(key)
        if not v:
            v = self.update_cache(tab_type, province_id)
            return v

        return json.loads(v)


words_cache = WordsCache()
