#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import multiprocessing

from django.core.management import BaseCommand
from gm_types.gaia import IMAGE_TYPE

from talos.models.diary.diary import Diary
from talos.models.diary.preoperationimage import PreOperationImage
from talos.models.topic.topicimage import TopicImage

file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sync_pre_imgs_new.log")


def _async_func(diary):
    try:
        if not diary.pre_operation_images.count():
            if diary.pre_operation_image:   # 并没有过滤空字符串的情况？！
                diary.pre_operation_images.create(
                    image_url=diary.pre_operation_image,
                    is_cover=True,
                    cover_image_url=diary.pre_operation_image
                )
                with open(file_path, "ab+") as f:
                    f.write("sync pre images to PreOperationImage,diary id:{0}\n".format(diary.id))

    except Exception as e:
        print e
        print u"error diary,is id:{0}".format(diary.id)


class Command(BaseCommand):
    """
    同步 帖子术前图 和 日记本术前封面图 到术前库
    """

    def handle(self, *args, **kwargs):
        print "start"
        
        pool = multiprocessing.Pool(processes=4)
        diaries = Diary.objects.filter(is_online=True, pre_operation_image__isnull=False).iterator()
        for diary in diaries:
            pool.apply_async(_async_func, (diary,))
        pool.close()
        pool.join()

        print "end"
