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

from datetime import datetime
from django.core.management import BaseCommand
from gm_upload.utils.image_utils import Picture
# from gm_upload import get_image_base_info

from talos.models.tractate import TractateImages


class Command(BaseCommand):
    """
    TractateImages 同步宽和高
    """
    # record_file = '/data/log/mimas/app/update_tractate_images.log'

    def handle(self, *args, **kwargs):
        record_file = '/data/log/mimas/app/update_tractate_images.log'
        with open(record_file, 'w') as f:
            f.write('start')
            # time_index = datetime.strptime('2019-04-26 00:00:00', "%y-%m-%d %H:%M:%S")
            pictures = TractateImages.objects.filter(width=0)
            f.write('count: {}'.format(pictures.count()))
            for item in pictures:
                try:
                    url = item.image_url
                    picture_info = Picture.get_image_base_info(url)
                    if not picture_info.get('width') or not picture_info.get('height'):
                        f.write("Can't find picture info, url: {}".format(url))
                    item.width = picture_info['width']
                    item.height = picture_info['height']
                    item.save()
                    f.write('Update success, url: {}'.format(url))
                except:
                    f.write("Update failed, url: {}".format(url))

            f.write('end')
