package ru.yandex.autotests.direct.api.campaigns.get.finance;

import java.util.Arrays;
import java.util.Collection;

import com.yandex.direct.api.v5.campaigns.CampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.CampaignFundsEnum;
import com.yandex.direct.api.v5.campaigns.CampaignGetItem;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.api.campaigns.CampaignsFeatures;
import ru.yandex.autotests.direct.api.campaigns.CampaignsLogins;
import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.direct.utils.money.Money;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.model.Logins;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignGetItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.FundsParamMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.SharedAccountFundsParamMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.directapi.steps.forecast.ApproximateNumbersMatchVariation;
import ru.yandex.autotests.irt.testutils.beandiffer.matchvariation.MatchVariation;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Issue;
import ru.yandex.qatools.allure.annotations.Issues;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static ru.yandex.autotests.directapi.matchers.beans.version5.BeanDifferMatcherV5.beanDifferV5;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;

/**
 * Created by ginger on 26.08.15.
 * https://st.yandex-team.ru/TESTIRT-6407
 */
@Aqua.Test
@Issues({
        @Issue("https://st.yandex-team.ru/DIRECT-34568"),
        @Issue("https://st.yandex-team.ru/DIRECT-45228")
})
@Features(CampaignsFeatures.GET)
@Description("Проверка значений поля Finance для кампании, подключенной к ОС")
@RunWith(Parameterized.class)
public class GetFinanceAccountModeTest {

    public static String client = CampaignsLogins.GET_ACCOUNT_CLIENT;

    @ClassRule
    public static ApiSteps api = new ApiSteps().version(5).as(client);

    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();

    @Rule
    public Trashman trasher = new Trashman(api);

    // В перл-версии campaigns.get нестабильно работает округление (какие-то значения меньше на 1, какие-то больше на 1)
    // Пока Campaigns.Get не переключится на Java, суммы будут проверяться приблизительно
    // TODO DIRECT-169007: убрать приблизительное сравнение после переключения Campaigns.Get на Java
    public static MatchVariation variation = new ApproximateNumbersMatchVariation(1, 100, true);

    private static Long textId;
    private static Long mobileAppId;
    private static Long dynamicTextId;

    @Parameterized.Parameter(0)
    public Float sum;

    @Parameterized.Parameter(1)
    public Float sumSpent;

    @Parameterized.Parameters(name = "sum = {0}, sum_spent = {1}")
    public static Collection testData() {
        Object[][] data = new Object[][]{
                {1000f, 0f},
                {0f, 1000f},
                {1000f, 0f},
                {1000f, 500f},
                {500f, 1000f},
                {1000f, 1000f},
                {0f, 0f},
                {-500f, -500f}
        };
        return Arrays.asList(data);
    }

    @BeforeClass
    public static void initTest() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
        api.as(Logins.SUPER_LOGIN).userSteps.financeSteps().enableSharedAccount(client);
        textId = api.as(client).userSteps.campaignSteps().addDefaultTextCampaign();
        mobileAppId = api.as(client).userSteps.campaignSteps().addDefaultMobileAppCampaign();
        dynamicTextId = api.as(client).userSteps.campaignSteps().addDefaultDynamicTextCampaign();
        int accountId = api.userSteps.financeSteps().getAccountID(client);
        api.userSteps.campaignFakeSteps()
                .setCampaignSum(accountId, 100);//чтобы заметить влияние ОС на суммы (его быть не должно)
    }

    @Before
    public void prepareCampaign() {
        api.userSteps.campaignFakeSteps().setCampaignSum(textId, sum);
        api.userSteps.campaignFakeSteps().setSumSpent(textId, sumSpent);
        api.userSteps.campaignFakeSteps().setCampaignSum(mobileAppId, sum);
        api.userSteps.campaignFakeSteps().setSumSpent(mobileAppId, sumSpent);
        api.userSteps.campaignFakeSteps().setCampaignSum(dynamicTextId, sum);
        api.userSteps.campaignFakeSteps().setSumSpent(dynamicTextId, sumSpent);
    }

    private Float calcRefund(Float sum, Float sumSpent) {
        Float refund = sum - sumSpent;
        return refund < 0 ? 0 : refund;
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("546")
    public void getFinanceOfTextCampaign() {
        //DIRECT-45228
        //DIRECT-46572
        Long expectedSpend = Money.valueOf(sumSpent, Currency.RUB).bidLong().longValueForSum();
        Long expectedRefund =
                Money.valueOf(calcRefund(sum, sumSpent), Currency.RUB).subtractVAT().bidLong().longValueForSum();
        CampaignGetItem campaignGetItem =
                api.userSteps.campaignSteps().campaignsGet(
                        textId,
                        CampaignFieldEnum.FUNDS
                );
        CampaignGetItem expectedCampaignGetItem = (CampaignGetItem) new CampaignGetItemMap()
                .withFunds(
                        new FundsParamMap()
                                .withMode(CampaignFundsEnum.SHARED_ACCOUNT_FUNDS)
                                .withSharedAccountFunds(
                                        new SharedAccountFundsParamMap()
                                                .withRefund(expectedRefund)
                                                .withSpend(expectedSpend)
                                )).getBean();
        assertThat("вернулось ожидаемое значение Finance", campaignGetItem,
                beanDifferV5(expectedCampaignGetItem).withVariation(variation));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("547")
    public void getFinanceOfMobileAppCampaign() {
        //DIRECT-45228
        //DIRECT-46572
        Long expectedSpend = Money.valueOf(sumSpent, Currency.RUB).bidLong().longValueForSum();
        Long expectedRefund =
                Money.valueOf(calcRefund(sum, sumSpent), Currency.RUB).subtractVAT().bidLong().longValueForSum();
        CampaignGetItem campaignGetItem =
                api.userSteps.campaignSteps().campaignsGet(
                        mobileAppId,
                        CampaignFieldEnum.FUNDS
                );
        CampaignGetItem expectedCampaignGetItem = (CampaignGetItem) new CampaignGetItemMap()
                .withFunds(
                        new FundsParamMap()
                                .withMode(CampaignFundsEnum.SHARED_ACCOUNT_FUNDS)
                                .withSharedAccountFunds(
                                        new SharedAccountFundsParamMap()
                                                .withRefund(expectedRefund)
                                                .withSpend(expectedSpend)
                                )).getBean();
        assertThat("вернулось ожидаемое значение Finance", campaignGetItem,
                beanDifferV5(expectedCampaignGetItem).withVariation(variation));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("548")
    public void getFinanceOfDynamicTextCampaign() {
        //DIRECT-45228
        //DIRECT-46572
        Long expectedSpend = Money.valueOf(sumSpent, Currency.RUB).bidLong().longValueForSum();
        Long expectedRefund =
                Money.valueOf(calcRefund(sum, sumSpent), Currency.RUB).subtractVAT().bidLong().longValueForSum();
        CampaignGetItem campaignGetItem =
                api.userSteps.campaignSteps().campaignsGet(
                        dynamicTextId,
                        CampaignFieldEnum.FUNDS
                );
        CampaignGetItem expectedGetItem = (CampaignGetItem) new CampaignGetItemMap()
                .withFunds(
                        new FundsParamMap()
                                .withMode(CampaignFundsEnum.SHARED_ACCOUNT_FUNDS)
                                .withSharedAccountFunds(
                                        new SharedAccountFundsParamMap()
                                                .withRefund(expectedRefund)
                                                .withSpend(expectedSpend)
                                )).getBean();
        assertThat("вернулось ожидаемое значение Finance", campaignGetItem,
                beanDifferV5(expectedGetItem).withVariation(variation));
    }
}
