package ru.yandex.autotests.direct.api.bidmodifiers.add;

import java.util.Arrays;

import org.apache.commons.lang3.StringUtils;
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.direct.api.bidmodifiers.BidModifiersFeatures;
import ru.yandex.autotests.direct.api.bidmodifiers.BidModifiersLogins;
import ru.yandex.autotests.direct.utils.beans.JsonObject;
import ru.yandex.autotests.directapi.ApiStories;
import ru.yandex.autotests.directapi.apiclient.config.ProtocolType;
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.model.api5.Action;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.BidModifierAddMap;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.DemographicsAdjustmentMap;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.MobileAdjustmentMap;
import ru.yandex.autotests.directapi.model.api5.general.MultiIdsExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.Notification;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.irt.testutils.allure.LogSteps;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.allure.annotations.Stories;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.equalTo;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
 * Created by chicos on 22.07.15
 */
@Aqua.Test
@Features(BidModifiersFeatures.ADD)
@Stories(ApiStories.UNITS)
@Description("Списание баллов при добавлении корректировок ставок")
public class AddBidModifiersUnitsTest {
    private LogSteps log = LogSteps.getLogger(this.getClass());
    private static final String singleClient = BidModifiersLogins.CLIENT_UNITS_ADD;

    private static final String agency = BidModifiersLogins.AGENCY_UNITS_ADD;
    private static final String subclient = BidModifiersLogins.SUBCLIENT_UNITS_ADD;

    @ClassRule
    public static ApiSteps api = new ApiSteps();

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

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

    private static final int ADD_COST = 15;
    private static final int ITEM_COST_ON_ADD = 1;
    private static final int ITEM_COST_ON_ADD_FAULT = 0;
    private static final int GENERAL_FAULT_COST = 50;

    private static Long groupID;
    private static Long agencyGroupID;

    private static Long clientCampaignID;
    private static Long agencyCampaignID;

    @BeforeClass
    public static void createGroup() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(singleClient);
        clientCampaignID = api.as(singleClient).userSteps.campaignSteps().addDefaultTextCampaign(singleClient);

        agencyCampaignID = api.as(agency).userSteps.campaignSteps().addDefaultTextCampaign(subclient);
        agencyGroupID = api.userSteps.adGroupsSteps().addDefaultGroup(agencyCampaignID, subclient);
    }

    @Before
    @Step("Подготовим данные для теста")
    public void prepareClient() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(singleClient);
        groupID = api.as(singleClient).userSteps.adGroupsSteps().addDefaultGroup(clientCampaignID);
    }

    @Test
    @Description("Добавление одиночной корректировки ставок")
    public void addSingleBidModifierTest() {
        api.as(singleClient);
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(singleClient);
        api.userSteps.bidModifiersSteps().addBidModifierMobileToGroup(groupID);
        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(singleClient);
        assertThat("стоимость добавления одной корректировки ставок", unitsBefore - unitsAfter, equalTo(ADD_COST + ITEM_COST_ON_ADD));
    }

    @Test
    @Description("Добавление нескольких корректировок ставок")
    public void addSeveralBidModifiersTest() {
        api.as(singleClient);
        BidModifierAddMap mobileModifier = new BidModifierAddMap()
                .withMobileAdjustment(new MobileAdjustmentMap().defaultMobileAdjustment())
                .withAdGroupId(groupID);
        BidModifierAddMap demographicsModifier = new BidModifierAddMap()
                .withDemographicsAdjustment(new DemographicsAdjustmentMap().defaultDemographicsAdjustment())
                .withAdGroupId(groupID);

        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(singleClient);
        api.userSteps.bidModifiersSteps().bidModifiersAdd(mobileModifier, demographicsModifier);
        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(singleClient);

        assertThat("стоимость добавления двух корректировок ставок", unitsBefore - unitsAfter, equalTo(ADD_COST + ITEM_COST_ON_ADD * 2));
    }

    @Test
    @Description("Добавление одной невалидной корректировки ставок")
    public void addInvalidBidModifierItemTest() {
        api.as(singleClient);
        BidModifierAddMap demographicsModifier =  new BidModifierAddMap()
                .withDemographicsAdjustment(new DemographicsAdjustmentMap().withDefaultBidModifier())
                .withCampaignId(clientCampaignID);

        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(singleClient);
        api.userSteps.bidModifiersSteps().shouldGetResultOn(
                Action.ADD,
                new AddRequestMap().withBidModifiers(demographicsModifier),
                MultiIdsExpectedResult.errors(new Notification(5008, Api5ErrorDetails.BID_MODIFIERS_AGE_OR_GENDER_REQUIRED)));
        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(singleClient);

        assertThat("стоимость ошибки при добавлении корректировки ставки", unitsBefore - unitsAfter, equalTo(ADD_COST + ITEM_COST_ON_ADD_FAULT));
    }

    @Test
    @Description("Добавление двух невалидных корректировок ставок")
    public void addFewInvalidBidModifiersTest() {
        api.as(singleClient);
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(singleClient);
        api.userSteps.bidModifiersSteps().shouldGetResultOn(
                Action.ADD,
                new AddRequestMap().withBidModifiers(new BidModifierAddMap()
                                .withDemographicsAdjustment(new DemographicsAdjustmentMap().withDefaultBidModifier())
                                .withAdGroupId(groupID),
                        new BidModifierAddMap()
                                .withMobileAdjustment(new MobileAdjustmentMap().withBidModifier(MobileAdjustmentMap.MOBILE_ADJUSTMENT_ABSOLUTE_MIN - 1))
                                .withAdGroupId(groupID)),
                MultiIdsExpectedResult.errors(new Notification(5008, Api5ErrorDetails.BID_MODIFIERS_AGE_OR_GENDER_REQUIRED)),
                MultiIdsExpectedResult.errors(new Notification(5005, Api5ErrorDetails.COEFFICIENT_VALUE_MUST_BE_A_POSITIVE_INTEGER)));
        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(singleClient);

        assertThat("стоимость ошибки при добавлении двух корректировок ставок", unitsBefore - unitsAfter, equalTo(ADD_COST + ITEM_COST_ON_ADD_FAULT * 2));
    }

    @Test
    @Description("Добавление одной корректной и одной невалидной корректировки ставок")
    public void addOneValidOneInvalidBidModifiersTest() {
        api.as(singleClient);
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(singleClient);
        api.userSteps.bidModifiersSteps().shouldGetResultOn(
                Action.ADD,
                new AddRequestMap().withBidModifiers(new BidModifierAddMap()
                                .withDemographicsAdjustment(new DemographicsAdjustmentMap().defaultDemographicsAdjustment())
                                .withAdGroupId(groupID),
                        new BidModifierAddMap()
                                .withMobileAdjustment(new MobileAdjustmentMap().withBidModifier(MobileAdjustmentMap.MOBILE_ADJUSTMENT_ABSOLUTE_MIN - 1))
                                .withAdGroupId(groupID)),
                MultiIdsExpectedResult.success(),
                MultiIdsExpectedResult.errors(new Notification(5005, Api5ErrorDetails.COEFFICIENT_VALUE_MUST_BE_A_POSITIVE_INTEGER)));
        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(singleClient);

        assertThat("стоимость ошибки при добавлении нескольких корректировок ставок",
                unitsBefore - unitsAfter, equalTo(ADD_COST + ITEM_COST_ON_ADD_FAULT + ITEM_COST_ON_ADD));
    }

    @Test
    @Description("Стоимость общей ошибки при добавлении корректировки ставок")
    public void generalErrorOnAddBidModifierTest() {
        api.as(singleClient);
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(singleClient);
        api.protocol(ProtocolType.SOAP).userSteps.bidModifiersSteps().shouldGetBidModifierErrorJsonOn(
                Action.ADD,
                new JsonObject().with("BidModifiers", Arrays.asList(123, 456, 789)),
                new Api5Error(8000, Api5ErrorDetails.ELEMENT_OF_ARRAY_MUST_CONTAIN_OBJECT,
                        StringUtils.capitalize(AddRequestMap.BID_MODIFIERS)),
                new Api5Error(8000, Api5ErrorDetailsJava.INVALID_VALUE,
                        StringUtils.capitalize(AddRequestMap.BID_MODIFIERS)));
        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(singleClient);

        assertThat("стоимость ошибки при добавлении корректировки ставок", unitsBefore - unitsAfter, equalTo(GENERAL_FAULT_COST));
    }

    @Test
    @Description("Недостаточное колличество баллов при добавлении корректировки ставок")
    public void notEnoughUnitsOnAddBidModifierTest() {
        api.as(singleClient);
        log.info("Обнулим колличество доступных пользователю баллов");
        int unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(singleClient);
        api.userSteps.clientFakeSteps().fakeWithdrawClientUnits(singleClient, unitsBefore);
        unitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(singleClient);
        assumeThat("доступные баллы пользователя", unitsBefore, equalTo(0));

        api.userSteps.bidModifiersSteps().shouldGetBidModifierErrorOn(
                Action.ADD,
                new AddRequestMap()
                        .withBidModifiers(new BidModifierAddMap()
                                .withMobileAdjustment(new MobileAdjustmentMap().defaultMobileAdjustment())
                                .withAdGroupId(groupID)),
                new Api5Error(152, Api5ErrorDetails.NOT_ENOUGH_UNITS_FOR_OPERATION));
        int unitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(singleClient);
        assertThat("доступные баллы пользователя после ошибки", unitsAfter, equalTo(0));
    }

    @Test
    @Description("Добавление агентством нескольких корректировок ставок")
    public void addBidModifiersUnitsCostByAgencyTest() {
        api.as(agency);
        BidModifierAddMap mobileModifier = new BidModifierAddMap()
                .withMobileAdjustment(new MobileAdjustmentMap().defaultMobileAdjustment())
                .withAdGroupId(agencyGroupID);
        BidModifierAddMap demographicsModifier = new BidModifierAddMap()
                .withDemographicsAdjustment(new DemographicsAdjustmentMap().defaultDemographicsAdjustment())
                .withAdGroupId(agencyGroupID);

        int agencyUnitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(agency);
        int scUnitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(subclient);
        api.userSteps.bidModifiersSteps().bidModifiersAdd(subclient,
                mobileModifier,
                demographicsModifier);
        int scUnitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(subclient);
        int agencyUnitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(agency);

        assertThat("списание баллов у агентства", agencyUnitsBefore - agencyUnitsAfter, equalTo(0));
        assertThat("списание баллов у субклиента", scUnitsBefore - scUnitsAfter, equalTo(ADD_COST + 2 * ITEM_COST_ON_ADD));
    }

    @Test
    @Description("Списание баллов у агентства при вызове метода без указания логина субклиента")
    public void unknownClientUnitsCostByAgencyTest() {
        api.as(agency);
        BidModifierAddMap demographicsModifier = new BidModifierAddMap()
                .withDemographicsAdjustment(new DemographicsAdjustmentMap().defaultDemographicsAdjustment())
                .withAdGroupId(agencyGroupID);

        int agencyUnitsBefore = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(agency);
        api.userSteps.bidModifiersSteps().shouldGetBidModifierErrorOn(
                Action.ADD,
                new AddRequestMap().withBidModifiers(demographicsModifier),
                new Api5Error(8000, Api5ErrorDetailsJava.NOT_CLIENT_IN_CLIENT_LOGIN));
        int agencyUnitsAfter = api.userSteps.clientFakeSteps().fakeClientUnitsBalance(agency);

        assertThat("списание баллов у агентства", agencyUnitsBefore - agencyUnitsAfter, equalTo(GENERAL_FAULT_COST));
    }
}
