# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-23 04:48
from __future__ import unicode_literals

from datetime import datetime

from django.db import migrations, models


def migrate_period_char_to_period_date(apps, schema_editor):
    """ Copy over the string in period_(start|end) to a date in period_(start|end)_date.

    Supported string formats:
      - None and ''
      - '2012-01-02'
      - '2012-01-2'
      - '1 Mar 2012'
      - '2013-02-01 00:00:00'
    As of 2016-09-23 all budget period_* in the production database have one of these formats.
    """
    Budget = apps.get_model("iati", "Budget")
    for budget in Budget.objects.all():
        for field_name in ('period_start', 'period_end'):
            date_string = getattr(budget, field_name)
            if date_string is None:
                date = None
            elif date_string == '':
                date = None
            else:
                try:
                    date = datetime.strptime(date_string, '%Y-%m-%d').date()
                except ValueError as e:
                    if e.message.startswith('unconverted data remains'):
                        # date_string looks like '2013-02-23 00:00:00'
                        date_string = date_string.split(' ')[0]
                        date = datetime.strptime(date_string, '%Y-%m-%d').date()
                    elif e.message.startswith('time data'):
                        # date_string looks like '1 Mar 2012'
                        date = datetime.strptime(date_string, '%d %b %Y').date()
                    else:
                        raise
            date_field_name = field_name + '_date'
            setattr(budget, date_field_name, date)
        budget.save()


class Migration(migrations.Migration):

    dependencies = [
        ('iati', '0005_auto_20160901_0034'),
    ]

    operations = [
        migrations.AddField(
            model_name='budget',
            name='period_start_date',
            field=models.DateField(blank=True, default=None, null=True),
        ),
        migrations.AddField(
            model_name='budget',
            name='period_end_date',
            field=models.DateField(blank=True, default=None, null=True),
        ),
        # Migrate the string in period_start to a date in period_start_date. Same for period_end
        migrations.RunPython(migrate_period_char_to_period_date),
        # remove the old fields
        migrations.RemoveField(model_name='budget', name='period_start'),
        migrations.RemoveField(model_name='budget', name='period_end'),
        # rename the new fields
        migrations.RenameField(model_name='budget', old_name='period_start_date', new_name='period_start'),
        migrations.RenameField(model_name='budget', old_name='period_end_date', new_name='period_end'),
    ]
