package ru.yandex.autotests.direct.api.bids.setauto.strategy;

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

import com.yandex.direct.api.v5.bids.BidFieldEnum;
import com.yandex.direct.api.v5.bids.BidGetItem;
import com.yandex.direct.api.v5.bids.CalculateByEnum;
import com.yandex.direct.api.v5.bids.ObjectFactory;
import com.yandex.direct.api.v5.general.PositionEnum;
import com.yandex.direct.api.v5.general.PriorityEnum;
import com.yandex.direct.api.v5.general.ScopeEnum;
import org.apache.commons.lang.StringUtils;
import org.hamcrest.Matcher;
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.BidsFeatures;
import ru.yandex.autotests.direct.api.bids.BidsLogins;
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.bids.BidExpectedResult;
import ru.yandex.autotests.directapi.model.api5.bids.BidSetAutoItemMap;
import ru.yandex.autotests.directapi.model.api5.bids.BidSetItemMap;
import ru.yandex.autotests.directapi.model.api5.bids.BidsGetItemMap;
import ru.yandex.autotests.directapi.model.api5.bids.SetAutoRequestMap;
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.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 ru.yandex.autotests.directapi.matchers.beandiffer2.BeanDifferMatcherV5.beanDifferV5;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
 * Created by gerdler on 25.04.17.
 */
@Aqua.Test
@Features(BidsFeatures.SET_AUTO)
@RunWith(Parameterized.class)
public class SetAutoAutotargetingsSearchOffAndManualNetworkTest {

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

    private static Long adGroupId;
    private static Long autotargetingId;
    private static Long campaignId;
    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 bidSet;

    @Parameterized.Parameter(2)
    public Matcher<Long> matcherForAutotargetingId;

    @Parameterized.Parameter(3)
    public Matcher<Long> matcherForAutotargetingId2;

    @Parameterized.Parameters(name = "{0}")
    public static Collection testData() {
        Object[][] data = new Object[][]{
                {
                        "on SEARCH and NETWORK by AutotargetingId",
                        (Runnable)() -> api.userSteps.bidsSteps().shouldGetBidResultOnSetAuto(
                                new SetAutoRequestMap().withBids(
                                        new BidSetAutoItemMap()
                                                .withKeywordId(autotargetingId)
                                                .withPosition(PositionEnum.FOOTERFIRST)
                                                .withIncreasePercent(50)
                                                .withCalculateBy(CalculateByEnum.VALUE)
                                                .withContextCoverage(3)
                                                .withMaxBid(MAX_SET_AUTO_BID)
                                                .withScope(ScopeEnum.SEARCH, ScopeEnum.NETWORK),
                                        new BidSetAutoItemMap()
                                                .withKeywordId(autotargetingId2)
                                                .withPosition(PositionEnum.FOOTERFIRST)
                                                .withIncreasePercent(50)
                                                .withCalculateBy(CalculateByEnum.VALUE)
                                                .withContextCoverage(3)
                                                .withMaxBid(MAX_SET_AUTO_BID)
                                                .withScope(ScopeEnum.SEARCH, ScopeEnum.NETWORK)
                                ),
                                BidExpectedResult.errors(
                                        new Notification(6001,
                                                Api5ErrorDetails.SET_AUTO_DENIED_FOR_AUTOTARGETING,
                                                StringUtils.capitalize(BidSetItemMap.KEYWORD_ID),
                                                autotargetingId
                                        )
                                ),
                                BidExpectedResult.errors(
                                        new Notification(6001,
                                                Api5ErrorDetails.SET_AUTO_DENIED_FOR_AUTOTARGETING,
                                                StringUtils.capitalize(BidSetItemMap.KEYWORD_ID),
                                                autotargetingId2
                                        )
                                )
                        ),
                        equalTo(ORIGINAL_BID),
                        equalTo(ORIGINAL_BID)
                },
                {
                        "on SEARCH by AdGroupId",
                        (Runnable)() -> api.userSteps.bidsSteps().shouldGetBidResultOnSetAuto(
                                new SetAutoRequestMap().withBids(
                                        new BidSetAutoItemMap()
                                                .withAdGroupId(adGroupId)
                                                .withPosition(PositionEnum.FOOTERFIRST)
                                                .withIncreasePercent(50)
                                                .withCalculateBy(CalculateByEnum.VALUE)
                                                .withMaxBid(MAX_SET_AUTO_BID)
                                                .withScope(ScopeEnum.SEARCH),
                                        new BidSetAutoItemMap()
                                                .withAdGroupId(adGroupId2)
                                                .withPosition(PositionEnum.FOOTERFIRST)
                                                .withIncreasePercent(50)
                                                .withCalculateBy(CalculateByEnum.VALUE)
                                                .withMaxBid(MAX_SET_AUTO_BID)
                                                .withScope(ScopeEnum.SEARCH)
                                ),
                                BidExpectedResult.errors(new Notification(9601,
                                                Api5ErrorDetails.BIDS_WILL_NOT_APPLIED_BECAUSE_OF_SHOWS_DISABLED_ON_SEARCH)
                                ),
                                BidExpectedResult.errors(new Notification(9601,
                                        Api5ErrorDetails.BIDS_WILL_NOT_APPLIED_BECAUSE_OF_SHOWS_DISABLED_ON_SEARCH)
                                )
                        ),
                        equalTo(ORIGINAL_BID),
                        equalTo(ORIGINAL_BID)
                },
                {
                        "on NETWORK by AdGroupId",
                        (Runnable)() -> api.userSteps.bidsSteps().shouldGetBidResultOnSetAuto(
                                new SetAutoRequestMap().withBids(
                                        new BidSetAutoItemMap()
                                                .withAdGroupId(adGroupId)
                                                .withMaxBid(MAX_SET_AUTO_BID)
                                                .withContextCoverage(3)
                                                .withScope(ScopeEnum.NETWORK),
                                        new BidSetAutoItemMap()
                                                .withAdGroupId(adGroupId2)
                                                .withMaxBid(MAX_SET_AUTO_BID)
                                                .withContextCoverage(3)
                                                .withScope(ScopeEnum.NETWORK)
                                ),
                                BidExpectedResult.successWithAdGroupId(),
                                BidExpectedResult.successWithAdGroupId()
                        ),
                        equalTo(ORIGINAL_BID),
                        equalTo(ORIGINAL_BID)
                },
                {
                        "on SEARCH and NETWORK by AdGroupId",
                        (Runnable)() -> api.userSteps.bidsSteps().shouldGetBidResultOnSetAuto(
                                new SetAutoRequestMap().withBids(
                                        new BidSetAutoItemMap()
                                                .withAdGroupId(adGroupId)
                                                .withPosition(PositionEnum.FOOTERFIRST)
                                                .withIncreasePercent(50)
                                                .withCalculateBy(CalculateByEnum.VALUE)
                                                .withContextCoverage(3)
                                                .withMaxBid(MAX_SET_AUTO_BID)
                                                .withScope(ScopeEnum.SEARCH, ScopeEnum.NETWORK),
                                        new BidSetAutoItemMap()
                                                .withAdGroupId(adGroupId2)
                                                .withPosition(PositionEnum.FOOTERFIRST)
                                                .withIncreasePercent(50)
                                                .withCalculateBy(CalculateByEnum.VALUE)
                                                .withContextCoverage(3)
                                                .withMaxBid(MAX_SET_AUTO_BID)
                                                .withScope(ScopeEnum.SEARCH, ScopeEnum.NETWORK)
                                ),
                                BidExpectedResult.warningsWithAdGroupID(
                                        new Notification(10160,
                                        Api5ErrorDetails.CHANGE_BIDS_ON_SEARCH_NOT_ALLOWED_BECAUSE_SHOWS_DISABLED)
                                ),
                                BidExpectedResult.warningsWithAdGroupID(
                                        new Notification(10160,
                                                Api5ErrorDetails.CHANGE_BIDS_ON_SEARCH_NOT_ALLOWED_BECAUSE_SHOWS_DISABLED)
                                )
                        ),
                        equalTo(ORIGINAL_BID),
                        equalTo(ORIGINAL_BID)
                },
                {
                        "on SEARCH by CampaignId",
                        (Runnable)() -> api.userSteps.bidsSteps().shouldGetBidResultOnSetAuto(
                                new SetAutoRequestMap().withBids(
                                        new BidSetAutoItemMap()
                                                .withCampaignId(campaignId)
                                                .withPosition(PositionEnum.FOOTERFIRST)
                                                .withIncreasePercent(50)
                                                .withCalculateBy(CalculateByEnum.VALUE)
                                                .withMaxBid(MAX_SET_AUTO_BID)
                                                .withScope(ScopeEnum.SEARCH)
                                ),
                                BidExpectedResult.errors(
                                        new Notification(9601,
                                            Api5ErrorDetails.BIDS_WILL_NOT_APPLIED_BECAUSE_OF_SHOWS_DISABLED_ON_SEARCH)
                                )
                        ),
                        equalTo(ORIGINAL_BID),
                        equalTo(ORIGINAL_BID)
                },
                {
                        "on NETWORK by CampaignId",
                        (Runnable)() -> api.userSteps.bidsSteps().shouldGetBidResultOnSetAuto(
                                new SetAutoRequestMap().withBids(
                                        new BidSetAutoItemMap()
                                                .withCampaignId(campaignId)
                                                .withMaxBid(MAX_SET_AUTO_BID)
                                                .withContextCoverage(3)
                                                .withScope(ScopeEnum.NETWORK)
                                ),
                                BidExpectedResult.successWithCampaignId()
                        ),
                        equalTo(ORIGINAL_BID),
                        equalTo(ORIGINAL_BID)
                },
                {
                        "on SEARCH and NETWORK by CampaignId",
                        (Runnable)() -> api.userSteps.bidsSteps().shouldGetBidResultOnSetAuto(
                                new SetAutoRequestMap().withBids(
                                        new BidSetAutoItemMap()
                                                .withCampaignId(campaignId)
                                                .withPosition(PositionEnum.FOOTERFIRST)
                                                .withIncreasePercent(50)
                                                .withCalculateBy(CalculateByEnum.VALUE)
                                                .withContextCoverage(3)
                                                .withMaxBid(MAX_SET_AUTO_BID)
                                                .withScope(ScopeEnum.SEARCH, ScopeEnum.NETWORK)
                                ),
                                BidExpectedResult.warningsWithCampaignID(
                                        new Notification(10160,
                                            Api5ErrorDetails.CHANGE_BIDS_ON_SEARCH_NOT_ALLOWED_BECAUSE_SHOWS_DISABLED)
                                )
                        ),
                        equalTo(ORIGINAL_BID),
                        equalTo(ORIGINAL_BID)
                },
        };
        return Arrays.asList(data);
    }

    @BeforeClass
    @Step("Подготовка данных для теста")
    public static void createKeywordsAndAutotargetings() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(BidsLogins.BIDS_CLIENT);
        campaignId = api.userSteps.campaignSteps().addDefaultTextCampaignWithStrategies(
                new TextCampaignSearchStrategyAddMap().defaultServingOff(),
                new TextCampaignNetworkStrategyAddMap().defaultMaximumCoverage()
        );
    }

    @Before
    public void prepareData() {
        adGroupId = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        api.userSteps.adsSteps().addDefaultTextAd(adGroupId);
        autotargetingId = api.userSteps.keywordsSteps().addAutotargetingWithBidsAndStrategyPriority(adGroupId, ORIGINAL_BID, MAX_BID, PriorityEnum.HIGH);

        adGroupId2 = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        api.userSteps.keywordsSteps().addKeyword(adGroupId2, "kw1");
        api.userSteps.keywordsSteps().addKeyword(adGroupId2, "kw2");
        api.userSteps.keywordsSteps().addKeyword(adGroupId2, "kw3");
        api.userSteps.adsSteps().addDefaultTextAd(adGroupId2);
        autotargetingId2 = api.userSteps.keywordsSteps().addAutotargetingWithBidsAndStrategyPriority(adGroupId2, ORIGINAL_BID, MAX_BID, PriorityEnum.HIGH);

        assumeThat("у автотаргетингов правильные ставки",
                api.userSteps.bidsSteps().bidsGetByKeywordIdsWithFields(Arrays.asList(BidFieldEnum.BID, BidFieldEnum.STRATEGY_PRIORITY), autotargetingId, autotargetingId2).getBids(),
                beanDifferV5(
                        Arrays.asList(
                                new BidsGetItemMap().withBid(ORIGINAL_BID).withStrategyPriority(new ObjectFactory().createBidGetItemStrategyPriority(PriorityEnum.HIGH)).getBean(),
                                new BidsGetItemMap().withBid(ORIGINAL_BID).withStrategyPriority(new ObjectFactory().createBidGetItemStrategyPriority(PriorityEnum.HIGH)).getBean()
                        )
                )
        );

        bidSet.run();
    }

    @Test
    @TestCaseId("2784")
    public void testPriceOfAutotargetingId() {
        List<BidGetItem> bidsItemList = api.userSteps.bidsSteps()
                .bidsGetByKeywordIdsWithFields(Collections.singletonList(BidFieldEnum.BID), autotargetingId).getBids();
        assumeThat("получили ставку автотаргетинга", bidsItemList.size(), equalTo(1));
        assertThat("у автотаргетинга правильная ставка на поиске", bidsItemList.get(0).getBid(), matcherForAutotargetingId);
    }

    @Test
    @TestCaseId("2785")
    public void testStrategyPriorityOfAutotargetingId() {
        List<BidGetItem> bidsItemList = api.userSteps.bidsSteps()
                .bidsGetByKeywordIdsWithFields(Collections.singletonList(BidFieldEnum.STRATEGY_PRIORITY), autotargetingId).getBids();
        assumeThat("получили приоритет автотаргетинга", bidsItemList.size(), equalTo(1));
        assertThat("у автотаргетинга правильный приоритет автостратегии",
                bidsItemList,
                beanDifferV5(
                        Collections.singletonList(
                                new BidsGetItemMap().withStrategyPriority(new ObjectFactory().createBidGetItemStrategyPriority(PriorityEnum.HIGH)).getBean()
                        )
                )
        );
    }

    @Test
    @TestCaseId("2786")
    public void testPriceOfAutotargetingId2() {
        List<BidGetItem> bidsItemList = api.userSteps.bidsSteps()
                .bidsGetByKeywordIdsWithFields(Collections.singletonList(BidFieldEnum.BID), autotargetingId2).getBids();
        assumeThat("получили ставку автотаргетинга", bidsItemList.size(), equalTo(1));
        assertThat("у автотаргетинга правильная ставка на поиске", bidsItemList.get(0).getBid(), matcherForAutotargetingId2);
    }

    @Test
    @TestCaseId("2787")
    public void testStrategyPriorityOfAutotargetingId2() {
        List<BidGetItem> bidsItemList = api.userSteps.bidsSteps()
                .bidsGetByKeywordIdsWithFields(Collections.singletonList(BidFieldEnum.STRATEGY_PRIORITY), autotargetingId2).getBids();
        assumeThat("получили приоритет автотаргетинга", bidsItemList.size(), equalTo(1));
        assertThat("у автотаргетинга правильный приоритет автостратегии",
                bidsItemList,
                beanDifferV5(
                        Collections.singletonList(
                                new BidsGetItemMap().withStrategyPriority(new ObjectFactory().createBidGetItemStrategyPriority(PriorityEnum.HIGH)).getBean()
                        )
                )
        );
    }
}
