# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-28 18:49
from __future__ import unicode_literals

from django.db import migrations

from osmaxx.utils.polyfile_helpers import get_polyfile_names_to_file_mapping


def update_excerpt(excerpt, polyfile_path):
    from osmaxx.utils.polyfile_helpers import polyfile_to_geos_geometry
    geometry = polyfile_to_geos_geometry(polyfile_path)
    excerpt.bounding_geometry = geometry
    excerpt.save()


def update_countries(apps, schema_editor):  # noqa
    Excerpt = apps.get_model("excerptexport", "Excerpt")  # noqa
    done_countries = []
    for name, polyfile_path in get_polyfile_names_to_file_mapping().items():
        done_countries.append(name)
        existing_excerpts = list(Excerpt.objects.filter(excerpt_type='country', name=name))
        if len(existing_excerpts) == 0:
            excerpt = Excerpt.objects.create(
                is_public=True,
                name=name,
                excerpt_type='country',
            )
            update_excerpt(excerpt, polyfile_path)
        else:
            for excerpt in existing_excerpts:
                update_excerpt(excerpt, polyfile_path)
    # Remove old countries. Yes, this deletes the existing exports of those countries as well!
    Excerpt.objects.filter(excerpt_type='country').exclude(name__in=done_countries).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('excerptexport', '0038_remove_outputfile_file_old'),
    ]

    operations = [
        migrations.RunPython(update_countries)
    ]
