#coding=utf-8

import json

import redis
from django.conf import settings
from django.core.management.base import BaseCommand

from agile.services.tag import (get_all_tag_v3_id_names, get_tag_v3_first_demands_by_tag_v3_ids,
                                get_tag_v3_first_solutions_by_tag_v3_ids, get_tag_v3_positions_by_tag_v3_ids,
                                get_tag_v3_second_demands_by_tag_v3_ids,
                                get_tag_v3_second_solutions_by_tag_v3_ids)

redis_client = None
try:
    redis_client = redis.StrictRedis.from_url(settings.DORIS_URL)
except Exception as e:
    print(e)


tag_v3_names_key = "doris:search:tag_v3:names"
last_time_names = redis_client.smembers(tag_v3_names_key)

class Command(BaseCommand):
    """
    """
    def handle(self, *args, **options):
        print("start")

        tag_v3_key_prefix = "doris:search:tag_v3_mapping:"
        tag_id_names_list = get_all_tag_v3_id_names()
        all_tag_v3_names = set()

        # all names from sql
        for id_name_pair in tag_id_names_list:
            name = id_name_pair.get("name", "")
            all_tag_v3_names.add(name.encode("utf-8"))

        # exist names difference current names
        # delete them
        for name in last_time_names.difference(all_tag_v3_names):
            redis_client.delete(tag_v3_key_prefix + name)
            print("delete tag: " + name)

        # update exist names' key
        redis_client.srem(tag_v3_names_key, *last_time_names)
        redis_client.sadd(tag_v3_names_key, *all_tag_v3_names)

        # add mapping
        count = 0
        for id_name_pair in tag_id_names_list:
            name = id_name_pair.get("name", "")
            redis_key = tag_v3_key_prefix + name

            id_list = [str(id_name_pair.get("id", ""))]
            redis_value = json.dumps({
                "first_demands": get_tag_v3_first_demands_by_tag_v3_ids(id_list),
                "second_demands": get_tag_v3_second_demands_by_tag_v3_ids(id_list),
                "first_solutions": get_tag_v3_first_solutions_by_tag_v3_ids(id_list),
                "second_solutions": get_tag_v3_second_solutions_by_tag_v3_ids(id_list),
                "positions": get_tag_v3_positions_by_tag_v3_ids(id_list)
            })
            redis_client.set(redis_key, redis_value)
            count += 1

        print("update tag: " + str(count))
        # values = redis_client.get(redis_key)
        # loaded_data = json.loads(values.decode("utf-8"))
        # positions = loaded_data.get("positions", [])

        print("end")
