import datetime

from django.conf import settings
from django.core.management import BaseCommand
from gm_types.mimas import TRACTATE_CONTENT_LEVEL
from talos.cache.base import vote_cache
from talos.tools.vote_tool import VoteTool
from talos.models.tractate import TractateCheck, TractateVote, Tractate

valid_level = [TRACTATE_CONTENT_LEVEL.GENERAL, TRACTATE_CONTENT_LEVEL.FINE, TRACTATE_CONTENT_LEVEL.EXCELLENT]


class Command(BaseCommand):

    def handle(self, *args, **kwargs):
        print("BEGIN")
        now_date = datetime.datetime.now()
        start_time = now_date.replace(hour=15, minute=0) + datetime.timedelta(days=-1)
        end_time = now_date.replace(hour=15, minute=0)
        tractate_ids = set(TractateCheck.objects.using(settings.SLAVE_DB_NAME).filter(
            check_time__lte=end_time, check_time__gte=start_time, content_level__in=valid_level
        ).values_list('tractate_id', flat=True))
        tractate_vote_info = TractateVote.objects.using(settings.SLAVE_DB_NAME).filter(
            tractate_id__in=tractate_ids, is_fake=True
        ).values('tractate_id', 'create_time', 'id')
        need_cache_info = {}
        for info in tractate_vote_info:
            tractate = Tractate.objects.get(id=info['tractate_id'])
            need_cache_info[info['id']] = {
                'tv_id': info['id'],
                'create_time': info['create_time'],
                'user_id': tractate.user_id,
            }
        for key, value in need_cache_info.items():
            vote_tool = VoteTool(redis_c=vote_cache, user_id=value['user_id'], new_version=True)
            vote_tool.receive_tractate_vote(key, vote_time=value['create_time'])

        print('DONE')
