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

from decimal import Decimal
from django.db import migrations, models


def forward(apps, schema_editor):
    Reward = apps.get_model('core', 'Reward')
    RUBLES_IN_DOLLAR = Decimal('65.00')  # Средний курс за последний год
    to_usd = lambda rub: round(rub * Decimal('0.87') / RUBLES_IN_DOLLAR / Decimal('0.75'))
    to_rub = lambda usd: round(usd * Decimal('0.75') * RUBLES_IN_DOLLAR / Decimal('0.87'))
    for reward in Reward.objects.select_related('reporter').all():
        if reward.reporter.username == 'nn9899':
            continue  # Этому пользователю проставим по курсу на день создания выплаты. Выплат мало, проставим руками
        if reward.payment_amount_rur == Decimal('0') and reward.payment_amount_usd == Decimal('0'):
            if reward.payment_currency is not None:
                if reward.payment_currency == 1:  # RUB
                    reward.payment_amount_rur = reward.payment_amount
                    reward.payment_amount_usd = to_usd(reward.payment_amount)
                elif reward.payment_currency == 2:  # USD
                    reward.payment_amount_usd = reward.payment_amount
                    reward.payment_amount_rur = to_rub(reward.payment_amount)
                else:
                    raise RuntimeError('Invalid payment_currency for reward with pk={}: {}'.format(
                        reward.pk,
                        reward.payment_currency
                    ))
                reward.save(update_fields=['payment_amount_usd', 'payment_amount_rur'])


def backward(apps, schema_editor):
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('core', '0051_responsible'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='responsible',
            options={'verbose_name': 'person responsible for regular reward processing', 'verbose_name_plural': 'people responsible for regular reward processing'},
        ),
        migrations.AddField(
            model_name='reward',
            name='payment_amount_rur',
            field=models.DecimalField(default=0, max_digits=10, decimal_places=2),
        ),
        migrations.AddField(
            model_name='reward',
            name='payment_amount_usd',
            field=models.DecimalField(default=0, max_digits=10, decimal_places=2),
        ),
        migrations.AlterField(
            model_name='reward',
            name='payment_amount',
            field=models.DecimalField(null=True, max_digits=10, decimal_places=2, blank=True),
        ),
        migrations.AlterField(
            model_name='reward',
            name='payment_currency',
            field=models.IntegerField(blank=True, null=True, choices=[(1, 'currency.rur'), (2, 'currency.usd')]),
        ),
        migrations.RunPython(forward, backward),
    ]
