# coding=utf-8
from datetime import datetime, timedelta
from collections import defaultdict

from django.core.management import BaseCommand

from rpc.cache import sign_task_cache


class Command(BaseCommand):

    def handle(self, *args, **options):
        """ python manage.py sign_cache_task_sync """
        print("Begin")
        now = datetime.now()
        # 当天剩余过期时间
        residue_seconds = (now.replace(hour=23, minute=59, second=59) - now).seconds
        new_cache_key = u'sign_order_{user_id}'
        all_cached_keys = sign_task_cache.keys(u"sign_order_*")
        cache_data = defaultdict(set)
        for key in all_cached_keys:
            # key = 'sign_task_cache:sign_order_{user_id}_{special_id}'
            key = key.split(':')[1]
            try:
                _, _, user_id, _, special_id = key.split('_')
            except:
                continue

            cache_key = new_cache_key.format(user_id=user_id)
            cache_data[cache_key].add(special_id)

        for k, special_ids in dict(cache_data).items():
            special_ids = list(map(int, special_ids))
            sign_task_cache.sadd(k, *special_ids)
            sign_task_cache.expire(k, residue_seconds)

        print("Done")
