# -*- coding: utf-8 -*-
from __future__ import unicode_literals

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

from kfet.forms import KFetConfigForm


def adapt_settings(apps, schema_editor):
    Settings = apps.get_model("kfet", "Settings")
    db_alias = schema_editor.connection.alias
    obj = Settings.objects.using(db_alias)

    cfg = {}

    def try_get(new, old, type_field):
        try:
            value = getattr(obj.get(name=old), type_field)
            cfg[new] = value
        except Settings.DoesNotExist:
            pass

    try:
        subvention = obj.get(name="SUBVENTION_COF").value_decimal
        subvention_mult = 1 + subvention / 100
        reduction = (1 - 1 / subvention_mult) * 100
        cfg["kfet_reduction_cof"] = reduction
    except Settings.DoesNotExist:
        pass
    try_get("kfet_addcost_amount", "ADDCOST_AMOUNT", "value_decimal")
    try_get("kfet_addcost_for", "ADDCOST_FOR", "value_account")
    try_get("kfet_overdraft_duration", "OVERDRAFT_DURATION", "value_duration")
    try_get("kfet_overdraft_amount", "OVERDRAFT_AMOUNT", "value_decimal")
    try_get("kfet_cancel_duration", "CANCEL_DURATION", "value_duration")

    cfg_form = KFetConfigForm(initial=cfg)
    if cfg_form.is_valid():
        cfg_form.save()


class Migration(migrations.Migration):

    dependencies = [("kfet", "0053_created_at"), ("djconfig", "0001_initial")]

    operations = [
        migrations.RunPython(adapt_settings),
        migrations.RemoveField(model_name="settings", name="value_account"),
        migrations.DeleteModel(name="Settings"),
    ]
