# Generated by Django 3.1.7 on 2021-03-30 08:01

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


def fix_applications(apps, schema_editor):
    Berth = apps.get_model("resources", "Berth")
    BerthApplication = apps.get_model("applications", "BerthApplication")
    BerthSwitch = apps.get_model("applications", "BerthSwitch")

    with transaction.atomic():
        for switch in BerthSwitch.objects.all():
            identifier = switch.pier or "-"
            try:
                # Assign the correct berth to the switch
                berth = Berth.objects.get(
                    pier__harbor=switch.harbor,
                    pier__identifier__iexact=identifier,
                    number=switch.berth_number,
                )
                switch.berth = berth
                switch.save()
            except Berth.DoesNotExist as e:
                print(f"{switch.harbor.id},{switch.pier},{switch.berth_number}")


class Migration(migrations.Migration):

    dependencies = [
        ("resources", "0029_remove_pier_harbors_harbor"),
        ("applications", "0033_validate_boat_dimensions"),
    ]

    operations = [
        migrations.AddField(
            model_name="berthswitch",
            name="berth",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to="resources.berth",
                verbose_name="berth",
                null=True,
                blank=True,
            ),
        ),
        migrations.RunPython(fix_applications, reverse_code=migrations.RunPython.noop),
        migrations.AlterField(
            model_name="berthswitch",
            name="berth",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to="resources.berth",
                verbose_name="berth",
            ),
        ),
        migrations.RemoveField(
            model_name="berthswitch",
            name="berth_number",
        ),
        migrations.RemoveField(
            model_name="berthswitch",
            name="harbor",
        ),
        migrations.RemoveField(
            model_name="berthswitch",
            name="pier",
        ),
    ]
