package ru.yandex.autotests.direct.api.keywordbids.setauto;

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

import com.yandex.direct.api.v5.general.PriorityEnum;
import com.yandex.direct.api.v5.keywordbids.KeywordBidFieldEnum;
import com.yandex.direct.api.v5.keywordbids.KeywordBidGetItem;
import com.yandex.direct.api.v5.keywordbids.KeywordBidSearchFieldEnum;
import org.apache.commons.lang.StringUtils;
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.bids.BidsLogins;
import ru.yandex.autotests.direct.api.keywordbids.KeywordBidsFeatures;
import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.direct.utils.money.MoneyCurrency;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetails;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignNetworkStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignNetworkStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.general.Notification;
import ru.yandex.autotests.directapi.model.api5.keywordbids.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.keywordbids.KeywordBidExpectedResult;
import ru.yandex.autotests.directapi.model.api5.keywordbids.KeywordBidsSelectionCriteriaMap;
import ru.yandex.autotests.directapi.model.api5.keywordbids.KeywordBidsSetAutoItemMap;
import ru.yandex.autotests.directapi.model.api5.keywordbids.KeywordBidsSetItemMap;
import ru.yandex.autotests.directapi.model.api5.keywordbids.NetworkByCoverageBiddingRule;
import ru.yandex.autotests.directapi.model.api5.keywordbids.SearchByTrafficVolumeBiddingRule;
import ru.yandex.autotests.directapi.model.api5.keywordbids.SetAutoBiddingRule;
import ru.yandex.autotests.directapi.model.api5.keywordbids.SetAutoRequestMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.allure.annotations.TestCaseId;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

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

@Aqua.Test
@Features(KeywordBidsFeatures.SET_AUTO)
@RunWith(Parameterized.class)
public class SetAutoAutotargetingTest {

    private static final String CLIENT = BidsLogins.BIDS_CLIENT;
    private static final Long MAX_BID = MoneyCurrency.get(Currency.RUB).getLongMaxPrice().longValue();
    private static final Long MAX_SET_AUTO_BID = MAX_BID / 2L;

    private static Long adGroupId;
    private static Long autotargetingId;
    private static Long adGroupId2;
    private static Long autotargetingId2;

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

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

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

    @Parameterized.Parameter(0)
    public String description;

    @Parameterized.Parameter(1)
    public Runnable adGroupCreator;

    @Parameterized.Parameters(name = "{0}")
    public static Collection testData() {
        Long textCampaignId = api.userSteps.campaignSteps().addDefaultTextCampaignWithStrategies(
                new TextCampaignSearchStrategyAddMap().defaultHighestPosition(),
                new TextCampaignNetworkStrategyAddMap().defaultMaximumCoverage()
        );
        Long mobileAppCampaignId = api.userSteps.campaignSteps().addDefaultMobileAppCampaignWithStrategies(
                new MobileAppCampaignSearchStrategyAddMap().defaultHighestPosition(),
                new MobileAppCampaignNetworkStrategyAddMap().defaultMaximumCoverage()
        );

        Object[][] data = new Object[][]{
                {
                        "text campaign",
                        (Runnable) () -> {
                            adGroupId = api.userSteps.adGroupsSteps().addDefaultGroup(textCampaignId);
                            api.userSteps.adsSteps().addDefaultTextAd(adGroupId);
                            adGroupId2 = api.userSteps.adGroupsSteps().addDefaultGroup(textCampaignId);
                            api.userSteps.adsSteps().addDefaultTextAd(adGroupId2);
                        }
                },
                {
                        "mobile app campaign",
                        (Runnable) () -> {
                            adGroupId = api.userSteps.adGroupsSteps().addDefaultMobileGroup(mobileAppCampaignId);
                            api.userSteps.adsSteps().addDefaultMobileAppAd(adGroupId);
                            adGroupId2 = api.userSteps.adGroupsSteps().addDefaultMobileGroup(mobileAppCampaignId);
                            api.userSteps.adsSteps().addDefaultMobileAppAd(adGroupId2);
                        }
                }
        };
        return Arrays.asList(data);
    }

    @BeforeClass
    @Step("Подготовка данных для теста")
    public static void clearUnits() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(CLIENT);
    }

    @Before
    public void prepareData() {
        adGroupCreator.run();

        autotargetingId = api.userSteps.keywordsSteps()
                .addAutotargetingWithBidsAndStrategyPriority(adGroupId, MAX_BID, MAX_BID, PriorityEnum.HIGH);

        api.userSteps.keywordsSteps().addKeyword(adGroupId2, "kw1");
        api.userSteps.keywordsSteps().addKeyword(adGroupId2, "kw2");
        api.userSteps.keywordsSteps().addKeyword(adGroupId2, "kw3");
        autotargetingId2 = api.userSteps.keywordsSteps()
                .addAutotargetingWithBidsAndStrategyPriority(adGroupId2, MAX_BID, MAX_BID, PriorityEnum.HIGH);
    }

    @Test
    @TestCaseId("2959")
    public void setAutoByAutotargetingId() {
        api.userSteps.keywordBidsSteps().shouldGetKeywordBidResultOnSetAuto(
                new SetAutoRequestMap().withKeywordBids(
                        new KeywordBidsSetAutoItemMap()
                                .withKeywordId(autotargetingId)
                                .withBiddingRule(new SetAutoBiddingRule()
                                        .withSearchByTrafficVolume(new SearchByTrafficVolumeBiddingRule()
                                                .withTargetTrafficVolume(10)
                                                .withIncreasePercent(50)
                                                .withBidCeiling(MAX_SET_AUTO_BID)))
                ),
                KeywordBidExpectedResult.errors(
                        new Notification(6001,
                                Api5ErrorDetails.SET_AUTO_DENIED_FOR_AUTOTARGETING,
                                StringUtils.capitalize(KeywordBidsSetItemMap.KEYWORD_ID),
                                autotargetingId
                        )
                )
        );
    }

    private List<KeywordBidGetItem> getKeywordBidsWithSearchBid(Long keywordId) {
        return api.userSteps.keywordBidsSteps()
                .keywordBidsGet(new GetRequestMap().withSelectionCriteria(new KeywordBidsSelectionCriteriaMap()
                        .withKeywordIds(keywordId))
                        .withFieldNames(KeywordBidFieldEnum.KEYWORD_ID)
                        .withSearchFieldNames(KeywordBidSearchFieldEnum.BID))
                .getKeywordBids();
    }

    @Test
    @TestCaseId("2960")
    public void setAutoOnSearchByAdGroupIdInAdGroupWithoutKeywords() {
        api.userSteps.keywordBidsSteps().shouldGetKeywordBidResultOnSetAuto(
                new SetAutoRequestMap().withKeywordBids(
                        new KeywordBidsSetAutoItemMap()
                                .withAdGroupId(adGroupId)
                                .withBiddingRule(new SetAutoBiddingRule()
                                        .withSearchByTrafficVolume(new SearchByTrafficVolumeBiddingRule()
                                                .withTargetTrafficVolume(10)
                                                .withIncreasePercent(50)
                                                .withBidCeiling(MAX_SET_AUTO_BID)))
                ),
                KeywordBidExpectedResult.successWithAdGroupId()
        );

        Long keywordId = SetAutoAutotargetingTest.autotargetingId;
        List<KeywordBidGetItem> bidsItemList = getKeywordBidsWithSearchBid(keywordId);
        assumeThat("получили ставки автотаргетинга", bidsItemList.size(), equalTo(1));
        assertThat("ставка на поиске у автотаргетинга не изменилась",
                bidsItemList.get(0).getSearch().getBid(), equalTo(MAX_BID));
    }

    @Test
    @TestCaseId("2961")
    public void setAutoOnSearchByAdGroupIdInAdGroupWithKeywords() {
        api.userSteps.keywordBidsSteps().shouldGetKeywordBidResultOnSetAuto(
                new SetAutoRequestMap().withKeywordBids(
                        new KeywordBidsSetAutoItemMap()
                                .withAdGroupId(adGroupId2)
                                .withBiddingRule(new SetAutoBiddingRule()
                                        .withSearchByTrafficVolume(new SearchByTrafficVolumeBiddingRule()
                                                .withTargetTrafficVolume(10)
                                                .withIncreasePercent(50)
                                                .withBidCeiling(MAX_SET_AUTO_BID)))
                ),
                KeywordBidExpectedResult.successWithAdGroupId()
        );

        List<KeywordBidGetItem> bidsItemList = getKeywordBidsWithSearchBid(autotargetingId2);
        assumeThat("получили ставку автотаргетинга", bidsItemList.size(), equalTo(1));
        assertThat("ставка на поиске у автотаргетинга изменилась",
                bidsItemList.get(0).getSearch().getBid(), not(equalTo(MAX_BID)));
    }

    @Test
    @TestCaseId("2962")
    public void setAutoOnNetworkByAdGroupIdInAdGroupWithoutKeywords() {
        api.userSteps.keywordBidsSteps().shouldGetKeywordBidResultOnSetAuto(
                new SetAutoRequestMap().withKeywordBids(
                        new KeywordBidsSetAutoItemMap()
                                .withAdGroupId(adGroupId)
                                .withBiddingRule(new SetAutoBiddingRule()
                                        .withNetworkByCoverage(new NetworkByCoverageBiddingRule()
                                                .withTargetCoverage(100)
                                                .withBidCeiling(MAX_SET_AUTO_BID)))
                ),
                KeywordBidExpectedResult.successWithAdGroupId()
        );

        List<KeywordBidGetItem> bidsItemList = getKeywordBidsWithSearchBid(autotargetingId);

        assumeThat("получили ставку автотаргетинга", bidsItemList.size(), equalTo(1));
        assumeThat("ставка на поиске у автотаргетинга не изменилась",
                bidsItemList.get(0).getSearch().getBid(), equalTo(MAX_BID));
    }

    @Test
    @TestCaseId("2963")
    public void setAutoOnNetworkByAdGroupIdInAdGroupWithKeywords() {
        api.userSteps.keywordBidsSteps().shouldGetKeywordBidResultOnSetAuto(
                new SetAutoRequestMap().withKeywordBids(
                        new KeywordBidsSetAutoItemMap()
                                .withAdGroupId(adGroupId2)
                                .withBiddingRule(new SetAutoBiddingRule()
                                        .withNetworkByCoverage(new NetworkByCoverageBiddingRule()
                                                .withTargetCoverage(100)
                                                .withBidCeiling(MAX_SET_AUTO_BID)))
                ),
                KeywordBidExpectedResult.successWithAdGroupId()
        );

        List<KeywordBidGetItem> bidsItemList = getKeywordBidsWithSearchBid(autotargetingId2);

        assumeThat("получили ставку автотаргетинга", bidsItemList.size(), equalTo(1));
        assumeThat("ставка на поиске у автотаргетинга не изменилась",
                bidsItemList.get(0).getSearch().getBid(), equalTo(MAX_BID));
    }
}
