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, Folder, ItemMetadata, MetaCategory
from sorl.thumbnail import get_thumbnail
import os, csv, pprint, re, json, shutil

class Command(BaseCommand):
    help = "creates or updates folders"

    def add_arguments(self, parser):
        parser.add_argument(
            '--collection-id',
            dest='collection_id',
            default=False,
            help='create or update folders for the specified collection',
        )
        parser.add_argument(
            '--regexp',
            dest='regexp',
            default=False,
            help='regexp to extract folder',
        )
        parser.add_argument(
            '--dry-run',
            dest='dry_run',
            default=False,
            action='store_const',
            const=True,
            help='just print the results'
        )
        parser.add_argument(
            '--metadata',
            dest='metadata',
            default='inventory_number',
            help='item metadata to extract folder',
        )

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

            if not options.get("regexp"):
                raise ValueError("!!! No regexp specified !!!")

            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():
                value = getattr(item.metadatas, options['metadata'])

                m = re.search(options['regexp'], value)
                folder_id = m.group(1)

                if not Folder.objects.filter(original_id=folder_id).exists():
                    print('#### Will create folder "'+folder_id+'"') if options['dry_run'] else print('#### Creating folder "'+folder_id+'"')
                    if not options['dry_run']:
                        folder = Folder.objects.create(
                            collection = collection,
                            name = 'Dossier '+folder_id,
                            original_id = folder_id
                        )
                else:
                    print('#### Folder "'+folder_id+'" already exists')
                    folder = Folder.objects.get(original_id=folder_id)

                if not options['dry_run']:
                    item.folders.add(folder)

            print('## Nothing done (dry run)') if options['dry_run'] else print('## All done')

        except ValueError as e:
            print(str(e))
