# -*- coding: UTF-8 -*-
import imghdr
import json
import logging
import os
from contextlib import ExitStack
from io import BytesIO

from django.conf import settings
from django.core.management.base import CommandError
from django.db import transaction
from PIL import Image as ImagePIL

from iconolab.management.commands.importimages import BaseImportImagesCommand
from iconolab.models import Collection

if settings.IMPORT_LOGGER_NAME and settings.LOGGING['loggers'].get(settings.IMPORT_LOGGER_NAME, ''):
    logger = logging.getLogger(settings.IMPORT_LOGGER_NAME)
else:
    logger = logging.getLogger(__name__)

class Command(BaseImportImagesCommand):
    help = 'import collection image and file from a directory'

    def add_arguments(self, parser):
        parser.add_argument(
            'source_json',
            help='creates a new collection from a json file, must be an object with fields : '
                 '"name" (identifier), '
                 '"verbose_name" (proper title name), '
                 '"description" (description on homepage, html is supported), '
                 '"image" (image on homepages, is a path to a image file. A relative path is relative to the json file path") '
        )
        parser.add_argument(
            '--collection-image',
            dest='collection_image',
            default=False,
            help='The path to an image. override the one given in the json file'
        )

        parser.add_argument(
            '--no-jpg-conversion',
            action='store_true',
            dest='no-jpg-conversion',
            default=False,
            help='use this option if you only want the image copied and not converted'
        )

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

        print('# Logging with logger '+logger.name)
        logger.debug('# Initializing command with args: %r', options)

        print('# Checking collection args')
        collection_json_path = options.get('source_json')
        if not os.path.isfile(collection_json_path):
            print('### No %s json file was found in the source directory' % collection_json_path)
            raise CommandError('!!! Json file '+ collection_json_path +' was not found !!!')

        print('## Loading collection json')
        with open(collection_json_path) as json_fixture_file:
            collection_data = json.loads(json_fixture_file.read())
            coll_name = collection_data.get('name')
            if not coll_name:
                print('!!! Collection data key "name" is empty')
                raise CommandError('!!! Collection data key "name" is empty')
            if Collection.objects.filter(name=coll_name).exists():
                print(
                    '!!! A Collection with the provided name already exists!')
                raise CommandError('!!! A Collection with the provided name already exists!')

        with transaction.atomic():
            collection = Collection.objects.create(
                name=coll_name,
                verbose_name=collection_data.get('verbose_name', coll_name),
                description=collection_data.get('description', coll_name),
                link_text=collection_data.get('link_text'),
                link_url=collection_data.get('link_url'),
            )

            image_path = options.get('collection_image', None)

            if not image_path:
                image_path = collection_data.get('image')
                if image_path and not os.path.isabs(image_path):
                    image_path = os.path.join(
                        os.path.dirname(os.path.abspath(collection_json_path)),
                        image_path)


            _, ext = os.path.splitext(image_path)
            target_filename = "%s_image%s" % (coll_name, ext)

            content_image = None
            with ExitStack() as stack:
                if not options.get('no-jpg-conversion', False) and imghdr.what(image_path) != 'jpeg':
                    target_filename = "%s_image%s" % (coll_name, '.jpeg')
                    print("Convert image from %s to %s" % (image_path, target_filename))
                    image_convert = ImagePIL.open(image_path)
                    if not image_convert.mode == 'RGB':
                        image_convert = image_convert.convert('RGB')
                    content_image = stack.enter_context(BytesIO())
                    image_convert.save(content_image, "JPEG", quality=settings.IMG_JPG_DEFAULT_QUALITY)
                else:
                    content_image = stack.enter_context(open(image_path, 'rb'))
                collection.image.save(target_filename, content_image)
