# -*- coding: UTF-8 -*-
from gm_rpcd.all import bind
from libs.algorithms import variousness, region_division

import functools
import logging
import traceback

import json
from django.conf import settings

logger = logging.getLogger(__name__)
import redis
from libs.cache import redis_client

MAX_LOAD = 100
GROUP_SIZE = 10
variousness_per_10 = functools.partial(variousness, variety_size=GROUP_SIZE)


@bind('doris/search/query_wikitab_keyword')
def query_wiki_keyword(query, offset=0, size=10, flag=False):
    try:
        wiki_hot_keyword = HotKeyWord.fetch_keyword(query)
        if size == 5 and flag == True:
            return wiki_hot_keyword[:5]
        return {"wiki_hot_recommends": wiki_hot_keyword}
    except:
        logging.error("catch exception,err_msg:%s" % traceback.format_exc())
        return {"wiki_hot_recommends": []}


class HotKeyWord:

    @classmethod
    def fetch_keyword(cls, query):
        try:
            if isinstance(query, str):
                result = list()
                redis_key = "gaia:hot_wiki_keyword:city_id:" + str(query)
                redis_field_val_list = redis_client.get(redis_key)
                logging.info("get redis_field_val_lsit:%s" % redis_field_val_list)
                if redis_field_val_list and len(redis_field_val_list) > 0:
                    result = json.loads(str(redis_field_val_list, encoding="utf-8"))
                have_read_id_list = result if result else []
                wiki_hot_keyword = list()
                for item in have_read_id_list:
                    wiki_hot_keyword.append([item.get('wiki_name'), item.get('wiki_id'), item.get("wiki_type")])

                logging.info('new wiki res:%s' % wiki_hot_keyword)

                return wiki_hot_keyword
        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())
            return []
