# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-09-29 06:45
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion


def get_cash_dary(model, date_movement):
    info = {
        'opened_date__year': date_movement.year,
        'opened_date__month': date_movement.month,
        'opened_date__day': date_movement.day,
        'opened_date__hour': date_movement.hour,
        'opened_date__minute': date_movement.minute
    }
    cash_diary = model.objects.filter(**info).first()
    if cash_diary is None:
        info.pop('opened_date__minute')
        cash_diary = model.objects.filter(**info).first()
        if cash_diary is None:
            info.pop('opened_date__hour')
            cash_diary = model.objects.filter(**info).first()
            if cash_diary is None:
                info.pop('opened_date__day')
                cash_diary = model.objects.filter(**info).first()
                if cash_diary is None:
                    info.pop('opened_date__month')
                    cash_diary = model.objects.filter(**info).first()
                    if cash_diary is None:
                        info.pop('opened_date__year')
                        cash_diary = model.objects.filter(**info).first()
                        if cash_diary is None:
                            cash_diary = model.objects.all().first()
                            if cash_diary is None:
                                raise Exception('CashDiary not found. Create one CashDiary for continue')
    return cash_diary


def run_migrate(apps, schema_editor):
    CashDiary = apps.get_model("codenerix_invoicing", "CashDiary")
    CashMovement = apps.get_model("codenerix_invoicing", "CashMovement")
    for x in CashMovement.objects.filter(cash_diary__isnull=True):
        cash_diary = get_cash_dary(CashDiary, x.date_movement)
        x.cash_diary = cash_diary
        x.save()


class Migration(migrations.Migration):

    dependencies = [
        ('codenerix_invoicing', '0056_cashmovement_reason'),
    ]

    operations = [
        migrations.RunPython(run_migrate),
        migrations.AlterField(
            model_name='cashmovement',
            name='cash_diary',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cash_movements', to='codenerix_invoicing.CashDiary', verbose_name='Cash diary'),
        ),
    ]
