# coding=utf-8
import json
from django.conf import settings
from django.core.management import BaseCommand
from rpc.cache import old_new_tag_mapping_cache as cache
from django.db import connections
from api.tool.log_tool import logging_exception


class Command(BaseCommand):
    """
    python manage.py tag_mapping_cache_data
    """
    cache_name = settings.TAT_MAPPING_HASH_NAME
    query = "select old_tag_id, agile_tag_id, api_agile_tag.name  " \
            "from api_agile_tag_mapping inner join api_agile_tag on " \
            "api_agile_tag_mapping.`agile_tag_id`= api_agile_tag.id " \
            "where api_agile_tag_mapping.is_online=true "

    def add_arguments(self, parser):
        parser.add_argument('-c', help='Reload or init redis tag mapping cache')

    def handle(self, *args, **options):
        result = 'success'
        count = 0
        connection = connections['default']
        try:
            call_method = options['c']
            if call_method :
                with connection.cursor() as cursor:
                    cursor.execute(self.query)
                    data = cursor.fetchall()
                if call_method == 'add':
                    count = self.add(data)
                elif call_method == 'reload':
                    count = self.reload(data)
        except Exception as ex:
            logging_exception()
            result = 'failure'
        finally:
            connection.close()
            print result,count

    def reload(self, data):
        """
        重新加载缓存
        :param data:
        :return:
        """ 
        all_keys = cache.hkeys(self.cache_name)
        if len(all_keys) > 0:
            pipe = cache.pipeline()
            for key in all_keys:
                pipe.hdel(self.cache_name, key)
            pipe.execute()
        return self.__set_redis(data)

    def add(self, data):
        """
        新增缓存
        :param data:
        :return:
        """
        return self.__set_redis(data)

    def __set_redis(self, data):
        if len(data) == 0:
            return 0
        pipe = cache.pipeline()
        for item in data:
            pipe.hset(self.cache_name, item[0], json.dumps({'id': item[1], 'name': item[2]}))
        data = pipe.execute()
        return len(data)
