# coding=utf-8

from django.core.management import BaseCommand

from api.models import User, Person, Problem, TopicVote
from rpc.cache import count_cache


class Command(BaseCommand):

    def handle(self, *args, **options):
        ps = Person.objects.all()
        total = ps.count()
        print 'total person: %s' % total

        ok_count = 0
        fail_count = 0

        for person in ps:
            try:
                topic_count = Problem.objects.filter(user=person.user).count()
                if topic_count:
                    key = "topic:%s:count" % person.id.hex
                    count_cache.set(key, topic_count)
                    print 'topic_count: ', person.topic_count, ' ', topic_count

                my_topics = Problem.objects.filter(user=person.user)
                if my_topics:
                    key = "vote:%s:count" % person.id.hex
                    c = sum(int(topic.vote_amount) for topic in my_topics)
                    if c:
                        count_cache.set(key, c)
                        print 'vote_count: ', person.vote_count, ' ', c

                ok_count += 1

            except:
                print person.id, ' failed'
                fail_count += 1

        print 'ok count: %s, fail count: %s, total count: %s' % (ok_count, fail_count, total)
