# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-27 18:19
from __future__ import unicode_literals

import logging

from django.db import migrations
from django.forms.models import model_to_dict


logger = logging.getLogger(__name__)


def forward(apps, schema_editor):
    Policy = apps.get_model('reqs', 'Policy')
    Requirement = apps.get_model('reqs', 'Requirement')
    policy_datas = Requirement.objects.values(
        'policy_number', 'policy_title', 'uri_policy_id', 'omb_policy_id',
        'policy_type', 'policy_issuance', 'policy_sunset'
    ).distinct()

    mapping = {}
    for row in policy_datas:
        policy_num = row['policy_number']
        if policy_num in mapping:
            logger.warning('Duplicate policy number:\nPrevious %s\nNew %s',
                           model_to_dict(mapping[policy_num]), row)
        else:
            mapping[policy_num] = Policy.objects.create(
                policy_number=int(policy_num), title=row['policy_title'],
                uri=row['uri_policy_id'], omb_policy_id=row['omb_policy_id'],
                policy_type=row['policy_type'], issuance=row['policy_issuance'],
                sunset=row['policy_sunset']
            )

    for policy_number, policy in mapping.items():
        Requirement.objects.filter(policy_number=policy_number).update(
            policy_id=policy.pk)


def backward(apps, schema_editor):
    Requirement = apps.get_model('reqs', 'Requirement')
    for req in Requirement.objects.prefetch_related('policy'):
        req.policy_number = str(req.policy.policy_number)
        req.policy_title = req.policy.title
        req.uri_policy_id = req.policy.uri
        req.omb_policy_id = req.policy.omb_policy_id
        req.policy_type = req.policy.policy_type
        req.policy_issuance = req.policy.issuance
        req.policy_sunset = req.policy.sunset

        req.save()


class Migration(migrations.Migration):
    dependencies = [('reqs', '0009_auto_20170127_2104')]
    operations = [migrations.RunPython(forward, backward)]
