package ru.yandex.autotests.direct.web.util.converters;

import java.math.RoundingMode;

import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.direct.utils.money.Money;
import ru.yandex.autotests.direct.utils.money.MoneyCurrency;
import ru.yandex.autotests.direct.utils.money.MoneyFormat;
import ru.yandex.autotests.direct.utils.strategy.objects.CampaignStrategyInfoWeb;
import ru.yandex.autotests.direct.utils.strategy.objects.StrategyInfoWeb;
import ru.yandex.autotests.direct.web.data.textresources.StrategiesResource;

import static ru.yandex.autotests.direct.web.util.beanutils.BeanHelper.getProperty;
import static ru.yandex.autotests.direct.web.util.beanutils.BeanHelper.setNotNullProperty;

public class Strategies {

    private static Currency currency;
    private static String locale;
    private static String abbreviation;


    private static String formatWithCurrency(Double money) {
        return Money.valueOf(money, currency).stringValue(MoneyFormat.INTEGER) + " " + abbreviation;
    }

    public static String getAlertText(String alertType, String alertParam) {
        if (alertType == null)
            return "";
        if (alertParam.equals(""))
            return StrategiesResource.getResourceByName(alertType).toString();
        return String.format(StrategiesResource.getResourceByName(alertType).toString(),
                alertParam);
    }

    public static void init(Currency currency, String locale) {
        Strategies.currency = currency;
        Strategies.locale = locale;
        Strategies.abbreviation = MoneyCurrency.get(currency).getAbbreviation(locale);
    }

    public static <T> void convertStrategyField(T bean, String fieldName, Currency currency) {
        if (getProperty(bean, fieldName) != null) {
            setNotNullProperty(bean, fieldName, Money.valueOf((Double) getProperty(bean, fieldName)).
                    convert(currency).setScale(2, RoundingMode.FLOOR).doubleValue());
        }
    }

    public static void convertStrategyCurrency(StrategyInfoWeb strategy, Currency currency) {
        CampaignStrategyInfoWeb bean = strategy.getCampaignStrategy();
        convertStrategyField(bean, "maxPrice", currency);
        convertStrategyField(bean, "weeklySumLimit", currency);
        convertStrategyField(bean, "averageCPA", currency);

        CampaignStrategyInfoWeb contextBean = strategy.getCampaignContextStrategy();
        convertStrategyField(contextBean, "maxPrice", currency);
        convertStrategyField(contextBean, "weeklySumLimit", currency);
        convertStrategyField(contextBean, "averageCPA", currency);

        convertStrategyField(strategy, "dayBudgetSum", currency);
    }
}