# Generated by Django 2.2.1 on 2019-09-20 07:59

from django.db import migrations
from model_utils import Choices


SCALES = Choices(
    (1, "commune", "Commune"),
    (5, "epci", "EPCI"),
    (8, "basin", "Bassin hydrographique"),
    (10, "department", "Département"),
    (15, "region", "Région"),
    (16, "overseas", "Outre-mer"),
    (17, "mainland", "Métropole"),
    (18, "adhoc", "Ad-hoc"),
    (20, "country", "Pays"),
    (25, "continent", "Continent"),
)


def create_mainland_overseas_perimeters(apps, schema_editor):
    """Handle mainland and overseas perimeters.

    - update mainland and overseas existing perimeters to the `adhoc` type;
    - set the `contained_in` link for all perimeters.
    """

    Perimeter = apps.get_model("geofr", "Perimeter")
    PerimeterContainedIn = Perimeter.contained_in.through
    containments = []

    mainland = Perimeter.objects.get(scale=SCALES.mainland)
    mainland.scale = SCALES.adhoc
    mainland.name = "France métropolitaine"
    mainland.save()

    mainland_perimeters = Perimeter.objects.filter(is_overseas=False).values_list(
        "id", flat=True
    )
    for perimeter_id in mainland_perimeters:
        containments.append(
            PerimeterContainedIn(
                from_perimeter_id=perimeter_id, to_perimeter_id=mainland.id
            )
        )

    overseas = Perimeter.objects.get(scale=SCALES.overseas)
    overseas.scale = SCALES.adhoc
    overseas.name = "Outre-mer"
    overseas.save()

    overseas_perimeters = Perimeter.objects.filter(is_overseas=True).values_list(
        "id", flat=True
    )
    for perimeter_id in overseas_perimeters:
        containments.append(
            PerimeterContainedIn(
                from_perimeter_id=perimeter_id, to_perimeter_id=overseas.id
            )
        )

    PerimeterContainedIn.objects.bulk_create(containments)


class Migration(migrations.Migration):

    dependencies = [
        ("geofr", "0023_auto_20190920_0958"),
    ]

    operations = [
        migrations.RunPython(create_mainland_overseas_perimeters),
    ]
