# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-06-09 04:59
from __future__ import unicode_literals

import datetime

# from django.core.management import call_command
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
# from django.utils.six import StringIO
import model_utils.fields

STORED_MIGRATION_DATA = {}


def update_translations(apps, schema_editor):
    pass
    # disabled due to later call in migration
    # call_command('update_translation_fields', stdout=StringIO())


def save_data(apps, schema_editor):
    Sector = apps.get_model('aims', 'Sector')
    SectorCategory = apps.get_model('aims', 'SectorCategory')
    ActivitySector = apps.get_model('aims', 'ActivitySector')

    STORED_MIGRATION_DATA['sector'] = list(Sector.objects.values(
        'date_created', 'date_modified', 'remote_data_id',
        'code', 'name', 'description', 'category_id',
        'name_en', 'name_tm', 'name_my', 'name_uz', 'name_ru'
    ))
    STORED_MIGRATION_DATA['sectorcategory'] = list(SectorCategory.objects.values(
        'date_created', 'date_modified', 'remote_data_id',
        'code', 'name', 'description', 'openly_type',
        'name_en', 'name_tm', 'name_my', 'name_uz', 'name_ru'
    ))
    STORED_MIGRATION_DATA['activitysector'] = list(ActivitySector.objects.values(
        'date_created', 'date_modified', 'remote_data_id',
        'id', 'alt_sector_name', 'percentage',
        'activity_id', 'activity__local_data__id', 'sector_id', 'vocabulary_id'
    ))


def restore_data(apps, schema_editor):
    def aware_time_from_naive_date(date):
        return datetime.datetime.combine(date, datetime.time(tzinfo=django.utils.timezone.get_current_timezone()))

    SectorCategory = apps.get_model('aims', 'SectorCategory')
    Sector = apps.get_model('aims', 'Sector')
    ActivitySector = apps.get_model('aims', 'ActivitySector')

    Sector.objects.all().delete()
    SectorCategory.objects.all().delete()
    ActivitySector.objects.all().delete()

    for data in STORED_MIGRATION_DATA['sectorcategory']:
        obj = SectorCategory.objects.create(code=data['code'], name=data['name'], description=data['description'], openly_type=data['openly_type'])
        obj.name_en = data['name']
        obj.name_tm = data['name_tm']
        obj.name_my = data['name_my']
        obj.name_ru = data['name_ru']
        obj.name_uz = data['name_uz']
        obj.save()
        if data['date_created']:
            created = aware_time_from_naive_date(data['date_created'])
            modified = aware_time_from_naive_date(data['date_modified']) if data['date_modified'] else created
            SectorCategory.objects.filter(code=data['code']).update(created=created, modified=modified)

    for data in STORED_MIGRATION_DATA['sector']:
        obj = Sector.objects.create(code=data['code'], name=data['name'], description=data['description'], category_id=data['category_id'])
        obj.name_en = data['name']
        obj.name_tm = data['name_tm']
        obj.name_my = data['name_my']
        obj.name_ru = data['name_ru']
        obj.name_uz = data['name_uz']
        obj.save()
        if data['date_created']:
            created = aware_time_from_naive_date(data['date_created'])
            modified = aware_time_from_naive_date(data['date_modified']) if data['date_modified'] else created
            Sector.objects.filter(code=data['code']).update(created=created, modified=modified)

    for data in STORED_MIGRATION_DATA['activitysector']:
        obj = ActivitySector.objects.create(id=data['id'], alt_sector_name=data['alt_sector_name'], percentage=data['percentage'],
                                            activity_id=data['activity__local_data__id'], sector_id=data['sector_id'], vocabulary_id=data['vocabulary_id'])
        if data['date_created']:
            created = aware_time_from_naive_date(data['date_created'])
            modified = aware_time_from_naive_date(data['date_modified']) if data['date_modified'] else created
            ActivitySector.objects.filter(id=data['id']).update(created=created, modified=modified)

    # update activitysector sequence - sql from `./manage.py sqlsequencereset aims | grep activitysector`
    schema_editor.execute('''SELECT setval(pg_get_serial_sequence('"aims_activitysector"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "aims_activitysector";''')


class Migration(migrations.Migration):
    atomic = False

    dependencies = [
        ('iati', '0014_aidtype_move_data'),
        ('aims', '0034_load_fixtures'),
    ]

    operations = [
        # record all pre migration data
        migrations.RunPython(save_data),

        # delete sector models
        migrations.RemoveField(
            model_name='sector',
            name='remote_data',
        ),
        migrations.RemoveField(
            model_name='sectorcategory',
            name='remote_data',
        ),
        migrations.DeleteModel(
            name='IATISector',
        ),
        migrations.DeleteModel(
            name='IATISectorCategory',
        ),
        migrations.DeleteModel(
            name='NationalSector',
        ),
        migrations.DeleteModel(
            name='NationalSectorCategory',
        ),
        migrations.DeleteModel(
            name='Sector',
        ),
        migrations.DeleteModel(
            name='SectorCategory',
        ),

        # recreate sector models
        migrations.CreateModel(
            name='Sector',
            fields=[
                ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
                ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
                ('code', models.IntegerField(primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=100)),
                ('description', models.TextField()),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='SectorCategory',
            fields=[
                ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
                ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
                ('code', models.IntegerField(primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=100)),
                ('description', models.TextField()),
                ('openly_type', models.CharField(choices=[('iati', 'Iati Codelist Sector'), ('national', 'National Sector')], default='iati', max_length=8)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.AddField(
            model_name='sector',
            name='category',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='aims.SectorCategory'),
        ),
        migrations.AddField(
            model_name='sector',
            name='name_en',
            field=models.CharField(max_length=100, null=True),
        ),
        migrations.AddField(
            model_name='sector',
            name='name_my',
            field=models.CharField(max_length=100, null=True),
        ),
        migrations.AddField(
            model_name='sector',
            name='name_ru',
            field=models.CharField(max_length=100, null=True),
        ),
        migrations.AddField(
            model_name='sector',
            name='name_tm',
            field=models.CharField(max_length=100, null=True),
        ),
        migrations.AddField(
            model_name='sector',
            name='name_uz',
            field=models.CharField(max_length=100, null=True),
        ),
        migrations.AddField(
            model_name='sectorcategory',
            name='name_en',
            field=models.CharField(max_length=100, null=True),
        ),
        migrations.AddField(
            model_name='sectorcategory',
            name='name_my',
            field=models.CharField(max_length=100, null=True),
        ),
        migrations.AddField(
            model_name='sectorcategory',
            name='name_ru',
            field=models.CharField(max_length=100, null=True),
        ),
        migrations.AddField(
            model_name='sectorcategory',
            name='name_tm',
            field=models.CharField(max_length=100, null=True),
        ),
        migrations.AddField(
            model_name='sectorcategory',
            name='name_uz',
            field=models.CharField(max_length=100, null=True),
        ),
        migrations.CreateModel(
            name='IATISector',
            fields=[
            ],
            options={
                'proxy': True,
            },
            bases=('aims.sector',),
        ),
        migrations.CreateModel(
            name='IATISectorCategory',
            fields=[
            ],
            options={
                'proxy': True,
            },
            bases=('aims.sectorcategory',),
        ),
        migrations.CreateModel(
            name='NationalSector',
            fields=[
            ],
            options={
                'proxy': True,
            },
            bases=('aims.sector',),
        ),
        migrations.CreateModel(
            name='NationalSectorCategory',
            fields=[
            ],
            options={
                'proxy': True,
            },
            bases=('aims.sectorcategory',),
        ),
        migrations.DeleteModel(
            name='ActivitySector',
        ),
        migrations.CreateModel(
            name='ActivitySector',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
                ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
                ('alt_sector_name', models.CharField(default='', max_length=200)),
                ('percentage', models.DecimalField(decimal_places=2, default=None, max_digits=5, null=True)),
                ('activity', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='iati.Activity')),
                ('sector', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='aims.Sector')),
                ('vocabulary', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='iati.Vocabulary')),
            ],
        ),
        migrations.AlterUniqueTogether(
            name='activitysector',
            unique_together=set([('activity', 'sector')]),
        ),
        migrations.RunPython(update_translations, atomic=True),
        migrations.RunPython(restore_data, atomic=True),
    ]
