# Generated by Django 3.1.3 on 2022-02-08 17:01

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


def migrate_parcels(apps, schema_editor):
    Geometry = apps.get_model('konova', 'Geometry')
    SpatialIntersection = apps.get_model('konova', 'SpatialIntersection')

    all_geoms = Geometry.objects.all()
    for geom in all_geoms:
        SpatialIntersection.objects.bulk_create([
            SpatialIntersection(geometry=geom, parcel=parcel)
            for parcel in geom.parcels.all()
        ])


class Migration(migrations.Migration):

    dependencies = [
        ('konova', '0002_auto_20220114_0936'),
    ]

    operations = [
        migrations.CreateModel(
            name='SpatialIntersection',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('calculated_on', models.DateTimeField(auto_now_add=True, null=True)),
                ('geometry', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='konova.geometry')),
                ('parcel', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='konova.parcel')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.RunPython(migrate_parcels),
        migrations.AddField(
            model_name='parcel',
            name='geometries_tmp',
            field=models.ManyToManyField(blank=True, related_name='parcels', through='konova.SpatialIntersection', to='konova.Geometry'),
        ),
        migrations.RemoveField(
            model_name='parcel',
            name='geometries',
        ),
        migrations.RenameField(
            model_name='parcel',
            old_name='geometries_tmp',
            new_name='geometries',
        ),
    ]
