# coding=utf-8

from django.core.management import BaseCommand, CommandError

from talos import Problem
from gm_types.gaia import TOPIC_TYPE

# copy api_problem with topy_type=topic_type.column_article to api_article
# Note: fill every word, esp is_online, create_at and update_at! every word!!!
from talos.models.topic.column import Article


class Command(BaseCommand):
    def handle(self, *args, **options):
        _max_num = 100
        all_articles = Problem.objects.filter(topic_type=TOPIC_TYPE.COLUMN_ARTICLE)
        articles, index = all_articles[:_max_num], 0
        while articles:
            for article in articles:
                self.copy_topic(article)
            self.stdout.write('*********finish num: %d' % len(articles))
            index += 1
            articles = all_articles[index * _max_num: (index + 1) * _max_num]

    def copy_topic(self, topic):
        try:
            Article._meta.get_field_by_name('created_time')[0].auto_now_add = False
            Article._meta.get_field_by_name('last_modified')[0].auto_now = False
            a = Article.objects.filter(article_id=topic.id)
            if a:
                # 在第一次部署后更改了，去同步
                if a[0].last_modified != topic.last_modified:
                    a[0].article_type = topic.topic_type
                    a[0].is_online = topic.is_online
                    a[0].save()
                    self.stdout.write('sync topic: %s success' % str(a[0].id))
            else:
                # create
                Article.objects.create(article_id=topic.id,
                                       article_type=topic.topic_type,
                                       is_online=topic.is_online,
                                       created_time=topic.created_time,
                                       last_modified=topic.last_modified)
                self.stdout.write('create Article id: %s, success' % (str(topic.id)))
        except Exception as e:
            self.stdout.write(str(e))
            print topic.title
            raise CommandError('error: topic id: %d' % topic.id)

