import boto3
from django.conf import settings
from django.core.management.base import BaseCommand

from establishment.models import EstablishmentSubType
from gallery.models import Image


class Command(BaseCommand):
    help = """
    Fill establishment type by index names.
    Steps: 
    1 Upload default images into s3 bucket
    2 Run command ./manage.py fill_artisan_default_image
    """

    def add_arguments(self, parser):
        parser.add_argument(
            '--template_image_folder_name',
            help='Template image folder in Amazon S3 bucket'
        )

    def handle(self, *args, **kwargs):
        not_updated = 0
        template_image_folder_name = kwargs.get('template_image_folder_name')
        if (template_image_folder_name and
            hasattr(settings, 'AWS_ACCESS_KEY_ID') and
            hasattr(settings, 'AWS_SECRET_ACCESS_KEY') and
            hasattr(settings, 'AWS_STORAGE_BUCKET_NAME')):
            to_update = []
            s3 = boto3.resource('s3')
            s3_bucket = s3.Bucket(settings.AWS_STORAGE_BUCKET_NAME)

            for object_summary in s3_bucket.objects.filter(Prefix=f'media/{template_image_folder_name}/'):
                uri_path = object_summary.key
                filename = uri_path.split('/')[-1:][0]
                if filename:
                    artisan_index_slice = filename.split('.')[:-1][0] \
                                                  .split('_')[2:]
                    if len(artisan_index_slice) > 1:
                        artisan_index_name = '_'.join(artisan_index_slice)
                    else:
                        artisan_index_name = artisan_index_slice[0]

                    attachment_suffix_url = f'{template_image_folder_name}/{filename}'

                    # check artisan in db
                    artisan_qs = EstablishmentSubType.objects.filter(index_name__iexact=artisan_index_name,
                                                                     establishment_type__index_name__iexact='artisan')
                    if artisan_qs.exists():
                        artisan = artisan_qs.first()
                        image, created = Image.objects.get_or_create(image=attachment_suffix_url,
                                                                     defaults={
                                                                         'image': attachment_suffix_url,
                                                                         'orientation': Image.HORIZONTAL,
                                                                         'title': f'{artisan.__str__()} '
                                                                                  f'{artisan.id} - '
                                                                                  f'{attachment_suffix_url}'})
                        if created:
                            # update artisan instance
                            artisan.default_image = image
                            to_update.append(artisan)
                        else:
                            not_updated += 1

            EstablishmentSubType.objects.bulk_update(to_update, ['default_image', ])
            self.stdout.write(self.style.WARNING(f'Updated {len(to_update)} objects.'))
            self.stdout.write(self.style.WARNING(f'Not updated {not_updated} objects.'))