# -*- coding: UTF-8 -*-
from django.core.management.base import BaseCommand, CommandError
from django.core.management import call_command
from django.conf import settings
from iconolab.models import Collection, Item, MetaCategory
from sorl.thumbnail import get_thumbnail
import os, csv, pprint, re, json, shutil

class Command(BaseCommand):
    help = "import images from a directory into the media folder and creates item and image objects"

    def add_arguments(self, parser):
        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',
        )

    def handle(self, *args, **options):
        try:
            if options.get("collection_id"):
                print("## Finding collection with id "+options.get("collection_id"))
                try:
                    collection = Collection.objects.get(pk=options.get("collection_id"))
                except Collection.DoesNotExist:
                    raise ValueError("!!! Collection with primary key "+options.get("collection_id")+" was not found, aborting !!!")
            else:
                raise ValueError("!!! No collection id, aborting because we don't know which collection to update. !!!")
            for item in collection.items.all():
                print("# Generating thumbnails for item: "+str(item.metadatas.natural_key))
                for image in item.images.all():
                    print("## Processing image "+str(image.name))
                    for size in settings.PREGENERATE_THUMBNAILS_SIZES:
                        print("### Size: "+size)
                        get_thumbnail(image.media, size, crop=False)
            print("## All done!")
        except ValueError as e:
            print(str(e))
