# Generated by Django 2.0.4 on 2018-04-23 08:47

import gzip
import json

import django.contrib.gis.db.models.fields
import os
from django.contrib.gis.geos import GEOSGeometry
from django.db import migrations, models
import django.db.models.deletion

DATA_PATH = os.path.join(os.path.dirname(__file__), 'data', '0008')


def forwards_func(apps, schema_editor):
    federal_subjects_with_region(apps, schema_editor, forward=True)


def reverse_func(apps, schema_editor):
    federal_subjects_with_region(apps, schema_editor, forward=False)


class Migration(migrations.Migration):

    dependencies = [
        ('regions', '0007_fill_timezones'),
    ]

    operations = [
        migrations.CreateModel(
            name='FederalSubjectWithPolygon',
            fields=[
                ('federalsubject_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='regions.FederalSubject')),
                ('polygon_location', django.contrib.gis.db.models.fields.GeometryField(srid=4326)),
                ('center', django.contrib.gis.db.models.fields.PointField(help_text='Задайте эту точку явно, если автоматически посчитанное значение отличается от желаемого', null=True, srid=4326, verbose_name='Точка центра')),
            ],
            options={
                'verbose_name': 'Федеральный субъект с гео',
                'verbose_name_plural': 'Федеральные субъекты с гео',
            },
            bases=('regions.federalsubject',),
        ),
        migrations.RunPython(forwards_func, reverse_func),
    ]


def federal_subjects_with_region(apps, schema_editor, forward=True):
    FederalSubject = apps.get_model("regions", "FederalSubject")
    FederalSubjectWithPolygon = apps.get_model("regions", "FederalSubjectWithPolygon")

    data_list = []
    with gzip.open(DATA_PATH + '/federal_subject_with_polygons.jsonl.gz', 'rt') as jsonl_file:
        for line in jsonl_file:
            id, wkt = read_jsonl(line)

            data = dict(polygon_location=GEOSGeometry(wkt),
                        **FederalSubject.objects.values().get(id=int(id)))
            data_list.append(data)

    if forward:
        for data in data_list:
            FederalSubjectWithPolygon(**data).save()
    else:
        for data in data_list:
            fswp = FederalSubjectWithPolygon.objects.get(id=data['id'])
            fswp.delete(keep_parents=True)  # this kwarg is not available on qs's delete() method


def read_jsonl(line):
    return json.loads(line.replace(r',\N', ',null'))
