# Generated by Django 2.0 on 2018-02-08 14:17

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

from hashids import Hashids


def generate_slug(value):
    """
    Generates a slug using a Hashid of `value`.

    Taken from spectator_core.models.SluggedModelMixin
    """
    # Defaults:
    alphabet = 'abcdefghijkmnopqrstuvwxyz23456789'
    salt = 'Django Spectator'

    if hasattr(settings, 'SPECTATOR_SLUG_ALPHABET'):
        alphabet = settings.SPECTATOR_SLUG_ALPHABET

    if hasattr(settings, 'SPECTATOR_SLUG_SALT'):
        salt = settings.SPECTATOR_SLUG_SALT

    hashids = Hashids(alphabet=alphabet, salt=salt, min_length=5)

    return hashids.encode(value)


def forwards(apps, schema_editor):
    """
    Re-save all the Works because something earlier didn't create their slugs.
    """
    Work = apps.get_model('spectator_events', 'Work')

    for work in Work.objects.all():
        if not work.slug:
            work.slug = generate_slug(work.pk)
            work.save()


class Migration(migrations.Migration):

    dependencies = [
        ('spectator_events', '0031_auto_20180208_1412'),
    ]

    operations = [
        migrations.RunPython(forwards),
    ]
