# Generated by Django 2.2.13 on 2020-07-13 18:22

from django.db import migrations, models
import django.db.models.deletion


def set_default_upstream_repository(apps, schema_editor):
    AnsibleRepository = apps.get_model('ansible', 'AnsibleRepository')
    SyncList = apps.get_model('galaxy', 'SyncList')

    db_alias = schema_editor.connection.alias

    synclists = SyncList.objects.using(db_alias).all()

    # Nothing to update
    if not synclists:
        return

    try:
        default_repo = AnsibleRepository.objects.using(db_alias).get(name="automation-hub")
    except AnsibleRepository.DoesNotExist:
        # If there are synclists, but no default repo, then let the exception raise
        if synclists:
            raise

    SyncList.objects.using(db_alias).all().update(upstream_repository=default_repo)


class Migration(migrations.Migration):

    dependencies = [
        ('ansible', '0018_fix_collection_relative_path'),
        ('galaxy', '0002_add_synclist_20200330_squashed'),
        ('core', '0032_export_to_chunks'),
    ]

    operations = [
        migrations.AddField(
            model_name='synclist',
            name='upstream_repository',
            field=models.ForeignKey(to='ansible.AnsibleRepository',
                                    on_delete=django.db.models.deletion.CASCADE,
                                    related_name='upstream_repositories',
                                    null=True),
            ),
        migrations.RunPython(code=set_default_upstream_repository),
        migrations.AlterField(
            model_name='synclist',
            name='upstream_repository',
            field=models.ForeignKey(to='ansible.AnsibleRepository',
                                    on_delete=django.db.models.deletion.CASCADE,
                                    related_name='upstream_repositories',
                                    null=False),
            ),
        migrations.AlterField(
            model_name='synclist',
            name='repository',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='repositories', to='ansible.AnsibleRepository'),
        ),
    ]
