# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-02-13 16:31
from __future__ import unicode_literals
import csv
import django.contrib.postgres.fields.jsonb
import os
from django.db import migrations

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


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


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


class Migration(migrations.Migration):

    dependencies = [
        ('regions', '0006_federalsubject_timezones'),
    ]

    operations = [
        migrations.RunPython(forwards_func, reverse_func),
        migrations.AlterField(
            model_name='federalsubject',
            name='timezones',
            field=django.contrib.postgres.fields.jsonb.JSONField(verbose_name='Часовые пояса'),
        ),
    ]


def make_timezone_json_entry(timezone, title):
    return dict(timezone=timezone, title=title)


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

    # timezones.csv is manually crafted from:
    # http://www.consultant.ru/document/cons_doc_LAW_165841/3d0cac60971a511280cbba229d9b6329c07731f7/#dst100031  # noqa
    with open(DATA_PATH + '/timezones.csv', 'rt') as f:
        reader = csv.DictReader(f, delimiter=';')
        for row in reader:
            qs = FederalSubject.objects.filter(id=row['id'], name=row['region'])
            if not forward:
                qs.update(timezones=None)
                continue

            tznames = [s for s in map(str.strip, row['tzname'].split(';')) if s]
            verbose_tznames = [s for s in map(str.strip, row['verbose_tzname'].split(';')) if s]

            if len(tznames) == 1:  # all except yakutia
                assert not len(verbose_tznames)
                timezones = [make_timezone_json_entry(timezone=tznames[0], title=tznames[0])]
            else:  # yakutia
                assert len(tznames) and len(tznames) == len(verbose_tznames)
                timezones = [make_timezone_json_entry(timezone=tz, title=t)
                             for tz, t in zip(tznames, verbose_tznames)]

            qs.update(timezones=timezones)
