# -*- coding: utf-8 -*-
# Generated by Django 1.11.21 on 2019-07-15 18:23


from datetime import datetime, timedelta
import glob
import os
import re
from shutil import copytree, rmtree

from django.conf import settings
from django.db import migrations


ALPHANUMERIC_ONLY = re.compile('\W+')
EVENTS_PATH = 'events'
DEST_DIRECTORY = os.path.join(settings.MEDIA_ROOT, settings.DEFAULT_MEDIA_PATH, EVENTS_PATH)
SRC_DIRECTORY = os.path.join(settings.DEFAULT_MEDIA_SRC_PATH, EVENTS_PATH)


def get_image_paths(location_name):
    """ Create image path, use alphanumeric name of the destination as the image filename """
    filename_glob = ALPHANUMERIC_ONLY.sub('', location_name) + '*.jpg'
    events_path = os.path.join(settings.DEFAULT_MEDIA_PATH, EVENTS_PATH, filename_glob)
    return glob.glob(events_path)


def get_sample_events():
    return [
        {
            'id': 999,
            'name': 'Crazy Philadelphia Eddie',
            'website_url': 'http://www.phillyseaport.org/Eddie',
            'description': '<p>Eddie was crazy before crazy was cool. From Brooklyn&#39;s Coney Island to the counterculture of 1960s South Street in Philadelphia, Eddie Funk fought to make a name for himself, protect the freedoms of tattoo artists, and share his legacy with the world. Discover Eddie&#39;s influence in this limited engagement exhibit, featuring rare flash, personal mementos, and other authentic memorabilia seldom put on public display.</p>',
            'published': True,
            'accessible': True,
            'start_date': datetime.now(),
            'end_date': datetime.now() + timedelta(days=365)
        },
    ]


def copy_default_images():
    """ Copy images to proper media dir """
    try:
        copytree(SRC_DIRECTORY, DEST_DIRECTORY)
    except OSError as e:
        # file exists error, rmtree is dumb and we can only copy to an empty directory
        if e.errno != 17:
            raise


def add_sample_events(apps, schema_editor):
    """ Add sample images to default destinations, and copy the images to the media dir """

    # Only run in development
    if not settings.DEBUG:
        return

    copy_default_images()

    Destination = apps.get_model('destinations', 'Destination')
    Event = apps.get_model('destinations', 'Event')
    for event in get_sample_events():
        event_destination = Destination.objects.get(name='Independence Seaport Museum')
        event['destination'] = event_destination
        sample_event = Event.objects.filter(name=event['name']).first()
        if not sample_event:
            sample_event = Event(**event)
            sample_event.save()
            paths = get_image_paths(event['name'])
            sample_event = Event.objects.filter(name=event['name']).first()
            image = paths.pop()
            image_wide = paths.pop()
            sample_event.image = image
            sample_event.image_raw = image
            sample_event.wide_image = image_wide
            sample_event.wide_image_raw = image_wide
            for path in paths:
                extra = sample_event.extraeventpicture_set.create()
                extra.image_raw = path
                extra.save()
                sample_event.extraeventpicture_set.add(extra)
            sample_event.save()


def delete_sample_events(apps, schema_editor):

    # Only run in development
    if not settings.DEBUG:
        return

    Event = apps.get_model('destinations', 'Event')
    for event in get_sample_events():
        try:
            sample_event = Event.objects.filter(name=event['name']).first()
            if sample_event:
                sample_event.extraeventpicture_set.all().delete()
                sample_event.save()
        except Event.DoesNotExist:
            pass

    # last delete the images in the media dir
    rmtree(DEST_DIRECTORY, True)


class Migration(migrations.Migration):

    dependencies = [
        ('destinations', '0045_prepopulate_multiple_images'),
    ]

    operations = [
        migrations.RunPython(add_sample_events, delete_sample_events),
    ]
