# -*- coding: UTF-8 -*-
import json
import logging
import os

from django.conf import settings
from django.core.management.base import CommandError
from django.db import transaction

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

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 metacategories files from a directory'

    def add_arguments(self, parser):
        parser.add_argument('metacategories_json')

        parser.add_argument(
            '--collection-id',
            dest='collection_id',
            default=False,
            help='insert extracted data into the specified collection instead of trying to load a collection fixture. the id is either a integer or a collection name',
        )

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

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

        collection = None
        collection_id = options.get('collection_id')

        if not collection_id:
            raise CommandError('!!! No collection fixture or collection id, aborting because we can\'t properly generate data. !!!')

        print('## Finding collection with id ' + collection_id)

        try:
            try:
                collection = Collection.objects.get(pk=int(collection_id))
            except ValueError:
                collection = Collection.objects.get(name=collection_id)
        except Collection.DoesNotExist:
            raise CommandError('!!! Collection with primary key ' + collection_id
                            +' was not found, aborting !!!')

        metacategories_json_path = options.get('metacategories_json')
        if not os.path.isfile(metacategories_json_path):
            print('### No '+metacategories_json_path+'.json file was found')
            raise CommandError(
                '!!! Fixture file '+metacategories_json_path+' was not found !!!')

        with open(metacategories_json_path) as metacategories_json_file, transaction.atomic():
            metacategories_data = json.load(metacategories_json_file)
            for metacategory in metacategories_data:
                if metacategory.get('label', None) is None:
                    raise CommandError(
                        '!!! Metacategory without label !!!')
                MetaCategory.objects.create(
                    collection=collection,
                    label=metacategory.get('label'),
                    triggers_notifications=metacategory.get(
                        'triggers_notifications', 0)
                )
