#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
__title__ = '同步历史数据：topic 数量到相应的diary'
__author__ = 'xierong@gmei.com'
__mtime__ = '18/1/5'
'''

import multiprocessing
from django.core.management import BaseCommand
from talos.models.diary import Diary, DiaryExtra


def AsyncTopicNums(diary):
    try:
        topics_count = diary.topics.filter(flag='n', is_online=True).count()
        if topics_count > 0:
            diary_extra = DiaryExtra()
            diary_extra.diary = diary
            diary_extra.topic_count = topics_count
            diary_extra.reply_count = 0
            diary_extra.vote_count = 0
            diary_extra.total_pv = 0
            diary_extra.save()

            print('diary - topic counts:{0}\t{1}'.format(diary.id, topics_count))

    except Exception, e:
        print(e)
        print('error,diary:{0}'.format(diary.id))


class Command(BaseCommand):

    def handle(self, *args, **options):

        pool = multiprocessing.Pool(processes=4)

        for diary in Diary.objects.filter(is_online=True).iterator():
            pool.apply_async(AsyncTopicNums, (diary,))

        pool.close()
        pool.join()