# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-11-01 16:12
from __future__ import unicode_literals

from django.db import migrations
from spectator.core.fields import AutoSlugField


def set_slug(apps, schema_editor):
    """
    Create a slug for each Event already in the DB.
    """
    Event = apps.get_model('spectator_events', 'Event')

    # We need to use AutoSlugField's methods to generate a slug for each
    # Event.
    asfield = AutoSlugField(populate_from='title', separator='-')
    asfield.attname = 'slug'

    for e in Event.objects.all():
        e.title_to_sort = event_str(e)
        e.slug = asfield.pre_save(e, True)
        e.save()

def event_str(event):
    """
    Pain in the arse. Can't access Event.title_to_sort() during the migration
    for some reason, so duplicating all this here just to get it working.
    """
    if event.title:
        return event.title
    else:
        if event.kind == 'concert':
            title = 'Concert #{}'.format(event.pk)
            if event.pk:
                # If it hasn't been saved (no pk) it has no classicalworks.
                works = [str(c) for c in event.classicalworks.all()]
                if len(works) == 1:
                    title = works[0]
                elif len(works) > 1:
                    title = '{} and {}'.format(
                                            ', '.join(works[:-1]),
                                            works[-1])
            return title

        elif event.kind == 'dance':
            title = 'Dance #{}'.format(event.pk)
            if event.pk:
                # If it hasn't been saved (no pk) it has no classicalworks.
                pieces = [str(p) for p in event.dancepieces.all()]
                if len(pieces) == 1:
                    title = pieces[0]
                elif len(pieces) > 1:
                    title = '{} and {}'.format(
                                            ', '.join(pieces[:-1]),
                                            pieces[-1])
            return title

        elif event.kind == 'movie':
            return str(event.movie)
        elif event.kind == 'play':
            return str(event.play)
        else:
            roles = list(event.roles.all())
            if len(roles) == 1:
                return str(roles[0].creator.name)
            elif len(roles) == 0:
                return 'Event #{}'.format(event.pk)
            else:
                roles = [r.creator.name for r in roles]
                # Join with commas but 'and' for the last one:
                return '{} and {}'.format(
                                        ', '.join(roles[:-1]),
                                        roles[-1])

class Migration(migrations.Migration):

    dependencies = [
        ('spectator_events', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='event',
            name='slug',
            field=AutoSlugField(blank=True, editable=False, null=True, populate_from='title'),
        ),
        migrations.RunPython(set_slug),
    ]
