package ru.yandex.autotests.direct.utils.converter;

import ch.lambdaj.function.convert.Converter;
import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.direct.utils.money.Money;
import ru.yandex.autotests.directapi.objecthelpers.uiclient.data.Row;
import java.math.RoundingMode;

/**
 * Created with IntelliJ IDEA.
 * User: mariabye
 * Date: 12.12.13
 * Time: 20:44
 * To change this template use File | Settings | File Templates.
 */
public class ReportSumConverter implements Converter<Row, Row> {
    private Currency currency;
    private boolean includeVAT;
    private boolean includeDiscount;
    private Money discount;
    private Double oldCurrencyRate;


    public ReportSumConverter(Currency currency, String includeVAT, String includeDiscount, Money discount) {
        this(currency, includeVAT, includeDiscount, discount, null);
    }


    public ReportSumConverter(
            Currency currency, String includeVAT, String includeDiscount, Money discount, Double oldCurrencyRate) {
        this.currency = currency;
        this.includeVAT = includeVAT.equals("Yes");
        this.includeDiscount = includeDiscount.equals("Yes");
        this.discount = discount;
        this.oldCurrencyRate = oldCurrencyRate;
    }

    @Override
    public Row convert(Row o) {
        Money sum = Money.valueOf(o.getSum(), currency)
                .convert(Currency.YND_FIXED, oldCurrencyRate).addVAT();
        Money sumSearch = Money.valueOf(o.getSum_search(), currency)
                .convert(Currency.YND_FIXED, oldCurrencyRate).addVAT();
        Money sumContext = Money.valueOf(o.getSum_context(), currency)
                .convert(Currency.YND_FIXED, oldCurrencyRate).addVAT();
        if (includeVAT || (currency == null)) {
            sum = sum.subtractVAT(currency);
            sumSearch = sumSearch.subtractVAT(currency);
            sumContext = sumContext.subtractVAT(currency);
        }
        if (includeDiscount && (currency != null)) {
            sum = sum.withDiscount(discount.doubleValue());
            sumSearch = sumSearch.withDiscount(discount.doubleValue());
            sumContext = sumContext.withDiscount(discount.doubleValue());
        }
        o.setSum(sum.setScale(2, RoundingMode.HALF_UP).floatValue());
        o.setSum_search(sumSearch.setScale(2, RoundingMode.HALF_UP).floatValue());
        o.setSum_context(sumContext.setScale(2, RoundingMode.HALF_UP).floatValue());
        return o;
    }
}
