package ru.yandex.autotests.directapi.dynamictextadtargets.setbids;

import java.util.List;

import com.yandex.direct.api.v5.dynamictextadtargets.StringConditionOperatorEnum;
import com.yandex.direct.api.v5.dynamictextadtargets.WebpageConditionOperandEnum;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.directapi.ApiStories;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.Api5Error;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetails;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetailsJava;
import ru.yandex.autotests.directapi.dynamictextadtargets.DynamicTextAdTargetsFeatures;
import ru.yandex.autotests.directapi.dynamictextadtargets.DynamicTextAdTargetsLogins;
import ru.yandex.autotests.directapi.model.api5.dynamictextadtargets.SetBidsItemMap;
import ru.yandex.autotests.directapi.model.api5.dynamictextadtargets.SetBidsRequestMap;
import ru.yandex.autotests.directapi.model.api5.dynamictextadtargets.WebpageAddItemMap;
import ru.yandex.autotests.directapi.model.api5.dynamictextadtargets.WebpageConditionMap;
import ru.yandex.autotests.directapi.model.api5.general.JavaOrPerlSetBidsExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.Notification;
import ru.yandex.autotests.directapi.model.api5.general.SetBidsActionResultMap;
import ru.yandex.autotests.directapi.model.api5.general.SetBidsExpectedResult;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
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.Stories;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.apache.commons.lang3.StringUtils.capitalize;
import static org.hamcrest.Matchers.equalTo;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;

/**
 * Created by semkagtn on 26.11.15.
 * https://st.yandex-team.ru/TESTIRT-7700
 */
@Aqua.Test
@Issue("https://st.yandex-team.ru/DIRECT-43826")
@Features(DynamicTextAdTargetsFeatures.SET_BIDS)
@Stories(ApiStories.UNITS)
@Description("Проверка списания баллов при вызове метода setBids")
public class SetBidsUnitsTest {

    private static final String LOGIN = DynamicTextAdTargetsLogins.UNITS_SET_BIDS_CLIENT;

    @ClassRule
    public static ApiSteps api = new ApiSteps().as(LOGIN);

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

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

    private static Long webpageId1;
    private static Long webpageId2;

    @BeforeClass
    public static void createWebpages() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(LOGIN);

        Long campaignId = api.userSteps.campaignSteps().addDefaultDynamicTextCampaign();
        Long adGroupId = api.userSteps.adGroupsSteps().addDefaultGroupDynamic(campaignId);
        List<Long> webpageIds = api.userSteps.dynamicTextAdTargetsSteps().addWebpages(
                new WebpageAddItemMap()
                        .withAdGroupId(adGroupId)
                        .withName("Name1")
                        .withConditions(new WebpageConditionMap()
                                .withOperand(WebpageConditionOperandEnum.PAGE_TITLE)
                                .withOperator(StringConditionOperatorEnum.CONTAINS_ANY)
                                .withArguments("arg1"))
                        .withBid(15_000_000L),
                new WebpageAddItemMap()
                        .withAdGroupId(adGroupId)
                        .withName("Name2")
                        .withConditions(new WebpageConditionMap()
                                .withOperand(WebpageConditionOperandEnum.PAGE_CONTENT)
                                .withOperator(StringConditionOperatorEnum.CONTAINS_ANY)
                                .withArguments("arg2"))
                        .withBid(15_000_000L));
        webpageId1 = webpageIds.get(0);
        webpageId2 = webpageIds.get(1);
    }

    @Before
    public void addUnitsToClient() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(LOGIN);
    }

    private static final int REQUEST_COST = 25;
    private static final int ITEM_COST = 0;
    private static final int ERROR_COST = 20;
    private static final int GENERAL_ERROR_COST = 50;

    @Test
    @Description("Один валидный элемент в запросе")
    public void oneValidElement() {
        int expectedCost = REQUEST_COST + ITEM_COST;
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);

        api.userSteps.dynamicTextAdTargetsSteps().shouldGetResultOnSetBids(new SetBidsRequestMap()
                        .withBids(new SetBidsItemMap()
                                .withId(webpageId1)
                                .withBid(20_000_000L)),
                SetBidsExpectedResult.successWithId());

        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        int actualCost = unitsBefore - unitsAfter;
        assertThat("списалось верное число баллов", actualCost, equalTo(expectedCost));
    }

    @Test
    @Description("Два валидных элемента в запросе")
    public void twoValidElements() {
        int expectedCost = REQUEST_COST + 2 * ITEM_COST;
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);

        api.userSteps.dynamicTextAdTargetsSteps().shouldGetResultOnSetBids(
                new SetBidsRequestMap().withBids(
                        new SetBidsItemMap()
                                .withId(webpageId1)
                                .withBid(20_000_000L),
                        new SetBidsItemMap()
                                .withId(webpageId2)
                                .withBid(20_000_000L)),
                SetBidsExpectedResult.successWithId(), SetBidsExpectedResult.successWithId());

        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        int actualCost = unitsBefore - unitsAfter;
        assertThat("списалось верное число баллов", actualCost, equalTo(expectedCost));
    }

    @Test
    @Description("Один невалидный элемент в запросе")
    public void oneInvalidElement() {
        int expectedCost = REQUEST_COST + ERROR_COST;
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);

        api.userSteps.dynamicTextAdTargetsSteps().shouldGetResultOnSetBids(
                new SetBidsRequestMap().withBids(
                        new SetBidsItemMap()
                                .withId(0L)
                                .withBid(20_000_000L)),
                SetBidsExpectedResult.errors(new Notification(5005, Api5ErrorDetails.FIELD_MUST_BE_POSITIVE_INTEGER,
                        capitalize(SetBidsActionResultMap.ID))));

        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        int actualCost = unitsBefore - unitsAfter;
        assertThat("списалось верное число баллов", actualCost, equalTo(expectedCost));
    }

    @Test
    @Description("Два невалидных элемента в запросе")
    public void twoInvalidElements() {
        int expectedCost = REQUEST_COST + 2 * ERROR_COST;
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);

        SetBidsExpectedResult perlError =
                SetBidsExpectedResult.errors(new Notification(9800));
        SetBidsExpectedResult javaError =
                SetBidsExpectedResult.errors(new Notification(9800,
                        Api5ErrorDetailsJava.OBJECT_CANNOT_BE_MORE_THAN_ONCE_IN_REQUEST));
        JavaOrPerlSetBidsExpectedResult javaAndPerlError = JavaOrPerlSetBidsExpectedResult
                .java(javaError)
                .perl(perlError);

        api.userSteps.dynamicTextAdTargetsSteps().shouldGetResultOnSetBids(
                new SetBidsRequestMap().withBids(
                        new SetBidsItemMap()
                                .withId(webpageId1)
                                .withBid(20_000_000L),
                        new SetBidsItemMap()
                                .withId(webpageId1)
                                .withBid(20_000_000L)),
                javaAndPerlError,
                javaAndPerlError);

        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        int actualCost = unitsBefore - unitsAfter;
        assertThat("списалось верное число баллов", actualCost, equalTo(expectedCost));
    }

    @Test
    @Description("Один валидный и один невалидный элемент в запросе")
    public void oneValidAndOneInvalidElements() {
        int expectedCost = REQUEST_COST + ITEM_COST + ERROR_COST;
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);

        api.userSteps.dynamicTextAdTargetsSteps().shouldGetResultOnSetBids(
                new SetBidsRequestMap().withBids(
                        new SetBidsItemMap()
                                .withId(webpageId1)
                                .withBid(20_000_000L),
                        new SetBidsItemMap()
                                .withId(0L)
                                .withBid(20_000_000L)),
                SetBidsExpectedResult.successWithId(),
                SetBidsExpectedResult.errors(new Notification(5005, Api5ErrorDetails.FIELD_MUST_BE_POSITIVE_INTEGER,
                        capitalize(SetBidsActionResultMap.ID))));

        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        int actualCost = unitsBefore - unitsAfter;
        assertThat("списалось верное число баллов", actualCost, equalTo(expectedCost));
    }

    @Test
    @Description("Невалидный запрос")
    public void invalidRequest() {
        int expectedCost = GENERAL_ERROR_COST;
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);

        api.userSteps.dynamicTextAdTargetsSteps().expectErrorOnDynamicTextAdTargetsSetBids(new SetBidsRequestMap()
                        .withBids(),
                new Api5Error(8000, Api5ErrorDetailsJava.FIELD_MUST_CONTAIN_NOT_LESS_ELEMENTS,
                        capitalize(SetBidsRequestMap.BIDS), 1));

        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(LOGIN);
        int actualCost = unitsBefore - unitsAfter;
        assertThat("списалось верное число баллов", actualCost, equalTo(expectedCost));
    }
}
