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

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

import com.yandex.direct.api.v5.bids.BidFieldEnum;
import com.yandex.direct.api.v5.bids.GetResponse;
import com.yandex.direct.api.v5.bids.ObjectFactory;
import com.yandex.direct.api.v5.general.PriorityEnum;
import org.junit.Before;
import org.junit.ClassRule;
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.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.apiclient.config.ProtocolType;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetails;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetailsJava;
import ru.yandex.autotests.directapi.model.api5.bids.BidExpectedResult;
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.BidsSelectionCriteriaMap;
import ru.yandex.autotests.directapi.model.api5.bids.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.bids.SetRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.general.Notification;
import ru.yandex.autotests.directapi.model.campaigns.MetrikaGoals;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.apache.commons.lang3.StringUtils.capitalize;
import static org.hamcrest.Matchers.anyOf;
import static ru.yandex.autotests.directapi.matchers.beandiffer2.BeanDifferMatcherV5.beanDifferV5;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;

/**
 * Created by ginger on 02.10.14.
 */
@Aqua.Test
@Features(BidsFeatures.SET)
@Tag(TagDictionary.TRUNK)
@RunWith(Parameterized.class)
public class SetPriorityShowsDisabledOnSearchAndAutoOnContextStrategyTest {

    private static final String CLIENT = BidsLogins.BIDS_CLIENT;
    private static final Long MIN_BID = MoneyCurrency.get(Currency.RUB).getLongMinPrice().longValue();
    private static final Long BID1 = MIN_BID * 2L;
    private static final Long BID2 = BID1 * 2L;

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

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

    @Parameterized.Parameter(value = 0)
    public String description;

    @Parameterized.Parameter(value = 1)
    public TextCampaignNetworkStrategyMap networkStrategy;

    private Long campaignID;
    private static final Long goalID = MetrikaGoals.getGoalForLogin(CLIENT);
    private Long keywordId;
    private Long autotargetingId;

    @Parameterized.Parameters(name = "{0}")
    public static Collection data() {
        return Arrays.asList(new Object[][]{
                {"SERVING_OFF + WB_MAXIMUM_CLICKS",
                        new TextCampaignNetworkStrategyMap().defaultWbMaximumClicks(Currency.RUB)},
                {"SERVING_OFF + WB_MAXIMUM_CONVERSION_RATE",
                        new TextCampaignNetworkStrategyMap().defaultWbMaximumConversionRate(Currency.RUB,
                                goalID)},
                {"SERVING_OFF + AVERAGE_CPC",
                        new TextCampaignNetworkStrategyMap().defaultAverageCpc(Currency.RUB)},
                {"SERVING_OFF + AVERAGE_CPA",
                        new TextCampaignNetworkStrategyMap().defaultAverageCpa(Currency.RUB, goalID)}
        });
    }

    @Before
    @Step("Подготовка данных для теста")
    public void createData() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(BidsLogins.BIDS_CLIENT);
        campaignID = api.userSteps.campaignSteps().addDefaultTextCampaign();
        api.userSteps.getDirectJooqDbSteps().useShardForLogin(CLIENT).campaignsSteps()
                .addCampMetrikaGoals(campaignID, goalID, 0L, 200L);
        api.userSteps.campaignSteps().campaignsUpdateWithCheck(new CampaignUpdateItemMap()
                .withId(campaignID)
                .withTextCampaign(new TextCampaignUpdateItemMap()
                        .withBiddingStrategy(new TextCampaignStrategyMap()
                                .withSearch(new TextCampaignSearchStrategyMap().defaultServingOff())
                                .withNetwork(networkStrategy))));
        Long adGroupId = api.userSteps.adGroupsSteps().addDefaultGroup(campaignID);
        api.userSteps.adsSteps().addDefaultTextAd(adGroupId);
        keywordId = api.userSteps.keywordsSteps()
                .addDefaultKeywordWithBidsAndStrategyPriority(adGroupId, BID1, BID1, PriorityEnum.NORMAL);
        autotargetingId = api.userSteps.keywordsSteps()
                .addAutotargetingWithBidsAndStrategyPriority(adGroupId, BID1, BID1, PriorityEnum.LOW);
        api.protocol(ProtocolType.SOAP);
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("1458")
    public void setStrategyPriorityTest() {
        api.userSteps.bidsSteps().shouldGetBidResultOnSet(
                new SetRequestMap()
                        .withBids(
                                new BidSetItemMap()
                                        .withCampaignId(campaignID)
                                        .withStrategyPriority(PriorityEnum.HIGH)
                        ),
                BidExpectedResult.successWithCampaignId()
        );

        GetResponse getResponse = api.userSteps.bidsSteps().bidsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new BidsSelectionCriteriaMap().withCampaignIds(campaignID)
                        )
                        .withFieldNames(BidFieldEnum.KEYWORD_ID, BidFieldEnum.STRATEGY_PRIORITY)
        );
        assertThat("получили правильные значения StrategyPriority",
                getResponse.getBids(),
                beanDifferV5(
                        Arrays.asList(
                                new BidsGetItemMap().withKeywordId(keywordId).withStrategyPriority(
                                        new ObjectFactory().createBidGetItemStrategyPriority(PriorityEnum.HIGH)
                                ).getBean(),
                                new BidsGetItemMap().withKeywordId(autotargetingId).withStrategyPriority(
                                        new ObjectFactory().createBidGetItemStrategyPriority(PriorityEnum.HIGH)
                                ).getBean()
                        )
                )
        );
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("1457")
    public void setBidAndContextBidAndStrategyPriorityTest() {
        //DIRECT-35448
        api.as(BidsLogins.BIDS_CLIENT).userSteps.bidsSteps().shouldGetBidResultOnSet(
                new SetRequestMap()
                        .withBids(
                                new BidSetItemMap()
                                        .withCampaignId(campaignID)
                                        .withBid(BID2)
                                        .withContextBid(BID2)
                                        .withStrategyPriority(PriorityEnum.HIGH)
                        ),
                BidsLogins.BIDS_CLIENT,
                BidExpectedResult.warningsWithCampaignID(
                        new Notification(10160, Api5ErrorDetails.BID_WILL_NOT_APPLIED_BECAUSE_OF_AUTO_STRATEGY,
                                capitalize(BidsGetItemMap.CONTEXT_BID)),
                        new Notification(10160,
                                Api5ErrorDetailsJava.BID_WILL_NOT_APPLIED_BECAUSE_OF_SHOWS_DISABLED_ON_SEARCH,
                                capitalize(BidSetItemMap.BID)))

        );

        GetResponse getResponse = api.userSteps.bidsSteps().bidsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new BidsSelectionCriteriaMap().withCampaignIds(campaignID)
                        )
                        .withFieldNames(BidFieldEnum.KEYWORD_ID, BidFieldEnum.BID, BidFieldEnum.CONTEXT_BID,
                                BidFieldEnum.STRATEGY_PRIORITY)
        );
        assertThat("получили правильные значения StrategyPriority",
                getResponse.getBids(),
                anyOf(
                        beanDifferV5( // для perl
                                Arrays.asList(
                                        new BidsGetItemMap().withKeywordId(keywordId).withBid(BID1).withContextBid(BID1)
                                                .withStrategyPriority(
                                                        new ObjectFactory()
                                                                .createBidGetItemStrategyPriority(PriorityEnum.HIGH)
                                                ).getBean(),
                                        new BidsGetItemMap().withKeywordId(autotargetingId).withBid(BID1)
                                                .withContextBid(BID1)
                                                .withStrategyPriority(
                                                        new ObjectFactory()
                                                                .createBidGetItemStrategyPriority(PriorityEnum.HIGH)
                                                ).getBean()
                                )
                        ), beanDifferV5( // для java
                                Arrays.asList(
                                        new BidsGetItemMap().withKeywordId(keywordId).withBid(BID1).withContextBid(BID1)
                                                .withStrategyPriority(
                                                        new ObjectFactory()
                                                                .createBidGetItemStrategyPriority(PriorityEnum.HIGH)
                                                ).getBean(),
                                        new BidsGetItemMap().withKeywordId(autotargetingId).withBid(BID1)
                                                .withContextBid(MIN_BID)
                                                .withStrategyPriority(
                                                        new ObjectFactory()
                                                                .createBidGetItemStrategyPriority(PriorityEnum.HIGH)
                                                ).getBean()
                                )))
        );
    }
}
