# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-06-12 20:35
from __future__ import unicode_literals

import datetime
import warnings

from django.core.management import call_command
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
from io import StringIO

import model_utils.fields

STORED_MIGRATION_DATA = {}


def update_translations(apps, schema_editor):
    call_command('update_translation_fields', stdout=StringIO())


def save_data(apps, schema_editor):
    Organisation = apps.get_model('aims', 'Organisation')

    STORED_MIGRATION_DATA['organisation'] = list(Organisation.objects.values(
        'date_created', 'date_modified', 'remote_data_id', 'is_admin',
        'code', 'abbreviation', 'type_id', 'name', 'reported_by_organisation', 'original_ref',
        'name_en', 'name_tm', 'name_my', 'name_uz', 'name_ru'
    ))


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()))

    # Transfer org types
    IatiOrganisationType = apps.get_model('iati', 'OrganisationType')
    OrganisationType = apps.get_model('aims', 'OrganisationType')
    for old in IatiOrganisationType.objects.all():
        serialized = old.__dict__
        del serialized['_state']
        OrganisationType.objects.create(**serialized)

    # Restor Organisations
    Organisation = apps.get_model('aims', 'Organisation')
    for data in STORED_MIGRATION_DATA['organisation']:
        obj = Organisation.objects.create(code=data['code'], name=data['name'], is_admin=data['is_admin'], abbreviation=data['abbreviation'], type_id=data['type_id'], reported_by_organisation=data['reported_by_organisation'], original_ref=data['original_ref'])  # type: Organisation
        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']
        try:
            obj.save()
        except Exception as E:
            warnings.warn('Unhandled legacy exception')
            warnings.warn(F'{E}')
            raise
        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
            Organisation.objects.filter(code=data['code']).update(created=created, modified=modified)


class Migration(migrations.Migration):
    atomic = False

    dependencies = [
        ('aims', '0035_activitysector_to_aims'),
    ]

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

        # remove old aims organisation model
        migrations.RemoveField(
            model_name='organisation',
            name='remote_data',
        ),
        migrations.DeleteModel(
            name='GovernmentOrganisation',
        ),
        migrations.DeleteModel(
            name='LocalMinistry',
        ),
        migrations.DeleteModel(
            name='Partner',
        ),
        migrations.AlterField(
            model_name='userorganisation',
            name='organisations',
            field=models.ManyToManyField(related_name='users', to='iati.Organisation'),
        ),
        migrations.DeleteModel(
            name='Organisation',
        ),

        # create new aims organisation model
        migrations.CreateModel(
            name='Organisation',
            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.CharField(max_length=80, primary_key=True, serialize=False)),
                ('abbreviation', models.CharField(default='', max_length=80)),
                ('reported_by_organisation', models.CharField(default='', max_length=100)),
                ('name', models.CharField(default='', max_length=250)),
                ('name_en', models.CharField(default='', max_length=250, null=True)),
                ('name_tm', models.CharField(default='', max_length=250, null=True)),
                ('name_my', models.CharField(default='', max_length=250, null=True)),
                ('name_uz', models.CharField(default='', max_length=250, null=True)),
                ('name_ru', models.CharField(default='', max_length=250, null=True)),
                ('original_ref', models.CharField(default='', max_length=80)),
                ('is_admin', models.BooleanField(default=False)),
            ],
        ),
        migrations.CreateModel(
            name='GovernmentOrganisation',
            fields=[
            ],
            options={
                'proxy': True,
            },
            bases=('aims.organisation',),
        ),
        migrations.CreateModel(
            name='LocalMinistry',
            fields=[
            ],
            options={
                'proxy': True,
            },
            bases=('aims.organisation',),
        ),
        migrations.CreateModel(
            name='Partner',
            fields=[
            ],
            options={
                'proxy': True,
            },
            bases=('aims.organisation',),
        ),
        migrations.CreateModel(
            name='OrganisationType',
            fields=[
                ('code', models.SmallIntegerField(primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=50)),
            ],
        ),
        migrations.AddField(
            model_name='organisation',
            name='type',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='aims.OrganisationType'),
        ),

        migrations.RunPython(restore_data, atomic=True),

        migrations.AlterField(
            model_name='activityendorsement',
            name='organisation',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='aims.Organisation'),
        ),
        migrations.AlterField(
            model_name='userorganisation',
            name='organisations',
            field=models.ManyToManyField(related_name='users', to='aims.Organisation'),
        ),
    ]
