# Generated by Django 2.2.13 on 2020-08:24 19:00

from django.db import migrations, transaction

from urllib.parse import urljoin


def fix_file_remote(apps, schema_editor):
    with transaction.atomic():
        Pulp2Importer = apps.get_model('pulp_2to3_migration', 'Pulp2Importer')
        Remote = apps.get_model('core', 'Remote')
        Pulp2LazyCatalog = apps.get_model('pulp_2to3_migration', 'Pulp2LazyCatalog')
        pulp2isoimporter_qs = Pulp2Importer.objects.filter(pulp2_type_id='iso_importer',
                                                           is_migrated=True)
        pulp2lazycatalog_to_update = []
        remotes_pk_to_delete = []
        for importer in pulp2isoimporter_qs:
            pulp2_config = importer.pulp2_config
            if pulp2_config.get('feed'):
                pulp2_config['feed'] = urljoin(pulp2_config['feed'], 'PULP_MANIFEST')
            remotes_pk_to_delete.append(importer.pulp3_remote.pk)
            # find LCEs
            pulp2lazycatalog = Pulp2LazyCatalog.objects.filter(
                pulp2_importer_id=importer.pulp2_object_id)
            for lce in pulp2lazycatalog:
                lce.is_migrated = False
            pulp2lazycatalog_to_update.extend(pulp2lazycatalog)
            importer.pulp2_config = pulp2_config
            importer.is_migrated = False
            importer.pulp3_remote = None

        Remote.objects.filter(pk__in=remotes_pk_to_delete).delete()
        Pulp2Importer.objects.bulk_update(objs=pulp2isoimporter_qs,
                                          fields=['is_migrated', 'pulp2_config', 'pulp3_remote'],
                                          batch_size=1000)
        Pulp2LazyCatalog.objects.bulk_update(objs=pulp2lazycatalog_to_update,
                                             fields=['is_migrated'],
                                             batch_size=1000)


class Migration(migrations.Migration):

    dependencies = [
        ('pulp_2to3_migration', '0012_size_bigint'),
    ]

    operations = [
        migrations.RunPython(fix_file_remote),
    ]
