# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-06 09:45
from __future__ import unicode_literals
import json
import os
from logging import getLogger

from django.db import migrations, connection

logger = getLogger(__name__)

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


def forwards_func(apps, schema_editor):
    federal_subject_types(apps, schema_editor, forward=True)
    federal_subjects(apps, schema_editor, forward=True)


def reverse_func(apps, schema_editor):
    federal_subjects(apps, schema_editor, forward=False)
    federal_subject_types(apps, schema_editor, forward=False)


class Migration(migrations.Migration):
    atomic = True

    dependencies = [
        ('regions', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(forwards_func, reverse_func),
    ]


def federal_subject_types(apps, schema_editor, forward=True):
    """
    SELECT distinct type
    FROM states
    INTO OUTFILE '/var/lib/mysql-files/state_types.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n';

    SELECT distinct typeShort
    FROM states
    INTO OUTFILE '/var/lib/mysql-files/state_types_short.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n';
    """
    FederalSubjectType = apps.get_model("regions", "FederalSubjectType")

    data_list = []
    with open(DATA_PATH + '/federal_subject_type.jsonl', 'rt') as jsonl_file:
        for line in jsonl_file:
            full_name, short_name, is_prefix = read_jsonl(line)
            data = dict(full_name=full_name, short_name=short_name, is_prefix=is_prefix == "1")
            data_list.append(data)

    if forward:
        FederalSubjectType.objects.bulk_create(
            FederalSubjectType(**data)
            for data in data_list
        )
        reset_sequence(FederalSubjectType)
    else:
        FederalSubjectType.objects.filter(
            full_name__in=list(data['full_name'] for data in data_list)
        ).delete()


def federal_subjects(apps, schema_editor, forward=True):
    """
    SELECT id,name,kladr_id,okato,type,typeShort,email
    FROM states
    INTO OUTFILE '/var/lib/mysql-files/states.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY ']\n[';
    """
    FederalSubjectType = apps.get_model("regions", "FederalSubjectType")
    FederalSubject = apps.get_model("regions", "FederalSubject")

    federal_subject_types = {
        fst.full_name: fst
        for fst in FederalSubjectType.objects.all()
    }

    data_list = []
    with open(DATA_PATH + '/federal_subject.jsonl', 'rt') as jsonl_file:
        for line in jsonl_file:
            id, name, kladr_id, okato, type_, type_short, email = read_jsonl(line)
            federal_subject_type = federal_subject_types[type_]
            assert type_short == federal_subject_type.short_name

            data = dict(pk=id, name=name, kladr_id=kladr_id,
                        federal_subject_type=federal_subject_type, email=email)
            data_list.append(data)

    if forward:
        FederalSubject.objects.bulk_create(
            FederalSubject(**data)
            for data in data_list
        )
        reset_sequence(FederalSubject)
    else:
        FederalSubject.objects.filter(pk__in=list(data['pk'] for data in data_list)).delete()


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


def reset_sequence(model):
    from django.core.management.color import no_style
    try:
        connection.cursor().execute(connection.ops.sequence_reset_sql(no_style(), [model])[0])
    except IndexError:
        # Only postgresql and oracle backends implement the sequence_reset_sql operation.
        # Other backends (sqlite, mysql) don't have sequences, thus nothing to reset here.
        # So it's safe to swallow this exception here.
        pass
