package ru.yandex.autotests.direct.api.campaigns.add.textcampaign.strategy.networkdefault;

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

import com.yandex.direct.api.v5.campaigns.AddResponse;
import com.yandex.direct.api.v5.campaigns.TextCampaignSettingsEnum;
import com.yandex.direct.api.v5.general.YesNoEnum;
import org.junit.Before;
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.campaigns.CampaignsFeatures;
import ru.yandex.autotests.direct.api.campaigns.CampaignsLogins;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.CampaignsRecord;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetails;
import ru.yandex.autotests.directapi.model.api5.campaigns.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyNetworkDefaultAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignAddItemMap;
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.campaigns.TextCampaignSettingMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
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.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.Step;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

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

/**
 * Created by gerdler on 26.02.2019.
 */
@Aqua.Test
@Features(CampaignsFeatures.ADD)
@Issue("https://st.yandex-team.ru/DIRECT-92407")
@RunWith(Parameterized.class)
@Description("Проверка получения предупреждений при указании параметра LimitPercent"
        + " при добавлении кампании со стратегией NetworkDefault и конверсионной стратегией на поиске")
public class StrategyNetworkDefaultAndConversionOnSearchTest {
    private static final String client = CampaignsLogins.CLIENT;
    private static final Currency currency = Currency.RUB;
    private static final Integer counterId = MetrikaGoals.getCounterForLogin(client);
    private static final Long goalId = MetrikaGoals.getGoalForCounter(counterId);

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

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

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

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

    @Parameterized.Parameter(value = 1)
    public TextCampaignSearchStrategyAddMap newSearchStrategy;

    @Parameterized.Parameters(name = "search = {0}")
    public static Collection strategies() {
        Object[][] data = new Object[][]{
                {"AverageCpa", new TextCampaignSearchStrategyAddMap().defaultAverageCpa(currency, goalId)},
                {"WbMaximumConversionRate",
                        new TextCampaignSearchStrategyAddMap().defaultWbMaximumConversionRate(currency, goalId)},
                {"AverageCpc", new TextCampaignSearchStrategyAddMap().defaultAverageCpc(currency)},
        };
        return Arrays.asList(data);
    }

    private static DirectJooqDbSteps jooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShardForLogin(client);

    @Before
    @Step("Подготовим данные для теста")
    public void prepare() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
    }

    @Test
    public void changeStrategyTest() {
        TextCampaignStrategyAddMap strategyMap = new TextCampaignStrategyAddMap()
                .withSearch(newSearchStrategy)
                .withNetwork(new TextCampaignNetworkStrategyAddMap().defaultNetworkDefaultWithLimitPercent());
        AddResponse response = api.userSteps.campaignSteps().shouldGetResultOnAdd(
                new AddRequestMap().withCampaigns(new CampaignAddItemMap()
                        .defaultCampaignAddItem()
                        .withTextCampaign(new TextCampaignAddItemMap()
                                .withBiddingStrategy(strategyMap)
                                .withSettings(
                                        new TextCampaignSettingMap()
                                                .withOption(TextCampaignSettingsEnum.MAINTAIN_NETWORK_CPC)
                                                .withValue(YesNoEnum.YES)
                                )
                        )),
                ExpectedResult.warningsIgnoringDetailsAndMessage(
                        new Notification(10165, Api5ErrorDetails.PARAM_WILL_NOT_BE_CHANGED, capitalize(
                                StrategyNetworkDefaultAddMap.LIMIT_PERCENT)),
                        new Notification(10163, Api5ErrorDetails.SETTING_WILL_NOT_BE_CHANGED,
                                TextCampaignSettingsEnum.MAINTAIN_NETWORK_CPC)
                )
        );
        CampaignsRecord newCampaignRecord =
                jooqDbSteps.campaignsSteps().getCampaignById(response.getAddResults().get(0).getId());
        assertThat("ContextLimit сохранился правильно", newCampaignRecord.getContextlimit(),
                equalTo(0));
        assertThat("ContextPriceCoef сохранился правильно", newCampaignRecord.getContextpricecoef(),
                equalTo(100));
        assertThat("opts сохранился правильно", newCampaignRecord.getOpts(),
                equalTo(""));
    }
}
