from django.conf import settings
from gm_rpcd.all import bind
import logging
import redis
import traceback

from libs.cache import redis_client


# from libs.feedbuilder import FeedBuilder

#
# @bind("doris/recommend/get_feeds")
# def get_feeds(device_id, feed_type, size=10, **kwargs):
#     """
#
#     :param device_id:
#     :param feed_type:
#     :param size:
#     :param kwargs: city_id:str, content_level:str, local:int, nearby:int, foreign:int
#     :return:
#     """
#     builder = FeedBuilder(ssdb_client, device_id, feed_type=feed_type)
#     data = builder.get(size, **kwargs)
#     return {feed_type: data}


def get_gm_kv_ins(redis_ip, redis_port, redis_db,redis_password=""):
    try:
        if len(redis_password)==0:
            cli_ins = redis.Redis(host=redis_ip, port=redis_port, db=redis_db, socket_timeout=2)
        else:
            cli_ins = redis.Redis(host=redis_ip, port=redis_port, db=redis_db, password=redis_password,socket_timeout=2)
        cli_ins.ping()

        return cli_ins
    except:
        return None


@bind("doris/recommend/user_portrait")
def get_user_portrait(device_id):
    try:
        gm_kv_ins = None
        for gm_kv_host_item in settings.GM_KV_HOSTS:
            gm_kv_ins = get_gm_kv_ins(redis_ip=gm_kv_host_item["host"], redis_port=gm_kv_host_item["port"], redis_db=gm_kv_host_item["db"],redis_password=gm_kv_host_item["password"])
            if gm_kv_ins:
                break

        ssdb_key = settings.DEVICE_PORTRAIT_NAME.format(device_id)
        category = gm_kv_ins.get(ssdb_key)
        if category:
            return {"portrait": int(category)}

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

