from django.db import migrations


def generate_slug(instance):
    slug = instance.slug
    i = 1
    while True:
        queryset = instance._meta.model.objects.filter(slug=slug, resource=instance.resource).exclude(
            pk=instance.pk
        )
        if not queryset.exists():
            break
        slug = '%s-%s' % (instance.slug, i)
        i += 1
    return slug


def set_slug(apps, schema_editor):
    Query = apps.get_model('csvdatasource', 'Query')
    for query in Query.objects.all().order_by('-pk'):
        if not Query.objects.filter(slug=query.slug, resource=query.resource).exclude(pk=query.pk).exists():
            continue
        query.slug = generate_slug(query)
        query.save(update_fields=['slug'])


class Migration(migrations.Migration):

    dependencies = [
        ('csvdatasource', '0013_auto_20181118_0807'),
    ]

    operations = [
        migrations.RunPython(set_slug, lambda x, y: None),
    ]
