package ru.yandex.autotests.directapi.dynamictextadtargets.add;

import com.yandex.direct.api.v5.dynamictextadtargets.AddResponse;
import com.yandex.direct.api.v5.dynamictextadtargets.StringConditionOperatorEnum;
import com.yandex.direct.api.v5.dynamictextadtargets.WebpageConditionOperandEnum;
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.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.dynamictextadtargets.DynamicTextAdTargetsFeatures;
import ru.yandex.autotests.directapi.dynamictextadtargets.DynamicTextAdTargetsLogins;
import ru.yandex.autotests.directapi.model.api5.dynamictextadtargets.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.dynamictextadtargets.WebpageAddItemMap;
import ru.yandex.autotests.directapi.model.api5.dynamictextadtargets.WebpageConditionMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.JavaOrPerlExpectedResult;
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.qa.balance.tools.common.utils.RandomDataUtils;
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;

/**
 * Created by ginger on 05.11.15.
 * https://st.yandex-team.ru/TESTIRT-6666
 */
@Aqua.Test
@Issue("https://st.yandex-team.ru/DIRECT-43826")
@Features(DynamicTextAdTargetsFeatures.ADD)
public class AddWebpagesMultipleTest {
    private static final String LOGIN = DynamicTextAdTargetsLogins.SINGLE_CLIENT_ADD;

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

    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();
    private static Long pid;
    private static AddResponse response;

    @Rule
    public Trashman trasher = new Trashman(api);
    private long nonExistedPid;
    private Long cid;
    private Long pid2;

    @BeforeClass
    public static void initTest() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(LOGIN);
    }

    @Before
    @Step("Подготовка данных для теста")
    public void createTestData() {

        cid = api.userSteps.campaignSteps().addDefaultDynamicTextCampaign(LOGIN);
        pid = api.userSteps.adGroupsSteps().addDefaultGroupDynamic(cid, LOGIN);
        pid2 = api.userSteps.adGroupsSteps().addDefaultGroupDynamic(cid, LOGIN);
        nonExistedPid = pid + 1000;
    }


    @Test
    @Description("Вызвать метод добавления условий нацеливания для существующей и несуществующей группы")
    public void tryAddWebpagesWithInvalidAdGroupId() {
        JavaOrPerlExpectedResult expectedResult = JavaOrPerlExpectedResult
                .java(ExpectedResult.errors(new Notification(8800, Api5ErrorDetails.GROUP_NOT_FOUND)
                        .withDetails("Группа объявлений не найдена")))
                .perl(ExpectedResult.errors(new Notification(8800, Api5ErrorDetails.GROUP_NOT_FOUND)));
        api.userSteps.dynamicTextAdTargetsSteps().shouldGetResultOnAdd(
                new AddRequestMap().withWebpages(
                        new WebpageAddItemMap()
                                .withConditions(new WebpageConditionMap()
                                        .withOperand(WebpageConditionOperandEnum.PAGE_TITLE)
                                        .withOperator(StringConditionOperatorEnum.CONTAINS_ANY)
                                        .withArguments("ginger")
                                )
                                .withName("Name1")
                                .withBid(30000000l)
                                .withAdGroupId(pid),
                        new WebpageAddItemMap()
                                .withConditions(new WebpageConditionMap()
                                        .withOperand(WebpageConditionOperandEnum.PAGE_CONTENT)
                                        .withOperator(StringConditionOperatorEnum.CONTAINS_ANY)
                                        .withArguments("ginger")
                                )
                                .withName("Name2")
                                .withBid(30000000l)
                                .withAdGroupId(nonExistedPid)
                ),
                JavaOrPerlExpectedResult.both(ExpectedResult.success()),
                expectedResult
        );
    }

    @Test
    @Description("Вызвать метод добавления условий нацеливания с одинаковыми Webpages")
    public void tryAddWebpagesWithSameAdGroupIds() {
        api.userSteps.dynamicTextAdTargetsSteps().shouldGetResultOnAdd(
                new AddRequestMap().withWebpages(
                        new WebpageAddItemMap()
                                .withConditions(new WebpageConditionMap()
                                        .withOperand(WebpageConditionOperandEnum.PAGE_TITLE)
                                        .withOperator(StringConditionOperatorEnum.CONTAINS_ANY)
                                        .withArguments("ginger")
                                )
                                .withName("Name1")
                                .withBid(30000000l)
                                .withAdGroupId(pid),
                        new WebpageAddItemMap()
                                .withConditions(new WebpageConditionMap()
                                        .withOperand(WebpageConditionOperandEnum.PAGE_TITLE)
                                        .withOperator(StringConditionOperatorEnum.CONTAINS_ANY)
                                        .withArguments("ginger")
                                )
                                .withName("Name1")
                                .withBid(30000000l)
                                .withAdGroupId(pid)
                ),
                JavaOrPerlExpectedResult.java(ExpectedResult.errors(new Notification(9800,
                        Api5ErrorDetailsJava.OBJECT_CANNOT_BE_MORE_THAN_ONCE_IN_REQUEST)))
                        .perl(ExpectedResult.errors(new Notification(9800))),
                JavaOrPerlExpectedResult.java(ExpectedResult.errors(new Notification(9800,
                        Api5ErrorDetailsJava.OBJECT_CANNOT_BE_MORE_THAN_ONCE_IN_REQUEST)))
                        .perl(ExpectedResult.errors(new Notification(9800)))
        );
    }

    @Test
    public void addSameWebpageInDifferentGroup() {
        api.userSteps.groupFakeSteps().getGroupParams(pid);
        api.userSteps.dynamicTextAdTargetsSteps().shouldGetResultOnAdd(
                new AddRequestMap().withWebpages(
                        new WebpageAddItemMap()
                                .withAdGroupId(pid)
                                .withName("Name")
                                .withConditions(
                                        new WebpageConditionMap()
                                                .withOperand(WebpageConditionOperandEnum.PAGE_TITLE)
                                                .withOperator(StringConditionOperatorEnum.CONTAINS_ANY)
                                                .withArguments("ginger"))
                                .withBid(30000000l),
                        new WebpageAddItemMap()
                                .withAdGroupId(pid2)
                                .withName("Name")
                                .withConditions(
                                        new WebpageConditionMap()
                                                .withOperand(WebpageConditionOperandEnum.PAGE_TITLE)
                                                .withOperator(StringConditionOperatorEnum.CONTAINS_ANY)
                                                .withArguments("ginger"))
                                .withBid(30000000l)
                ),
                ExpectedResult.success(),
                ExpectedResult.success()
        );
    }

    @Test
    public void tryAddPagesAllConditionAndPagesSubsetByOneRequest() {
        JavaOrPerlExpectedResult expectedResult = JavaOrPerlExpectedResult
                .java(ExpectedResult.errors(new Notification(6000,
                        Api5ErrorDetails.WEBPAGE_WITH_ALL_CONDITION_CAN_NOT_BE_WITH_ANOTHER_CONDITION)
                        .withDetails("Условие нацеливания с правилом `Все страницы` не может комбинироваться с " +
                                "другими условиями в группе"))
                )
                .perl(ExpectedResult.errors(new Notification(6000,
                        Api5ErrorDetails.WEBPAGE_WITH_ALL_CONDITION_CAN_NOT_BE_WITH_ANOTHER_CONDITION))
                );
        api.userSteps.dynamicTextAdTargetsSteps().shouldGetResultOnAdd(
                new AddRequestMap().withWebpages(
                        new WebpageAddItemMap()
                                .withAdGroupId(pid)
                                .withName("Name")
                                .withBid(30000000l),
                        new WebpageAddItemMap()
                                .withAdGroupId(pid)
                                .withName("Name")
                                .withConditions(
                                        new WebpageConditionMap()
                                                .withOperand(WebpageConditionOperandEnum.PAGE_TITLE)
                                                .withOperator(StringConditionOperatorEnum.CONTAINS_ANY)
                                                .withArguments("ginger"))
                                .withBid(30000000l)
                ),
                expectedResult,
                expectedResult);
    }

    @Test
    @Issue("DIRECT-48987")
    @Description("Добавление двух невалидных условий")
    public void checkNumerationInErrorInvalidWebpagesTest() {
        JavaOrPerlExpectedResult expectedResult = JavaOrPerlExpectedResult
                .java(ExpectedResult.errors(
                        new Notification(5004, Api5ErrorDetails.INVALID_FORMAT_WEBPAGE_CONDITION, 1)
                                .withDetails("Неправильный формат правила №1: задано неподдерживаемое отношение")))
                .perl(ExpectedResult.errors(
                        new Notification(5004, Api5ErrorDetails.INVALID_FORMAT_WEBPAGE_CONDITION, 1)));
        api.userSteps.dynamicTextAdTargetsSteps().shouldGetResultOnAdd(
                new AddRequestMap()
                        .withWebpages(
                                new WebpageAddItemMap()
                                        .withConditions(
                                                new WebpageConditionMap()
                                                        .withOperand(WebpageConditionOperandEnum.PAGE_TITLE)
                                                        .withOperator(StringConditionOperatorEnum.EQUALS_ANY)
                                                        .withArguments(RandomDataUtils.getRandomString(10))
                                        )
                                        .withName("Name1")
                                        .withBid(30000000l)
                                        .withAdGroupId(pid),
                                new WebpageAddItemMap()
                                        .withConditions(
                                                new WebpageConditionMap()
                                                        .withOperand(WebpageConditionOperandEnum.PAGE_CONTENT)
                                                        .withOperator(StringConditionOperatorEnum.NOT_EQUALS_ALL)
                                                        .withArguments(RandomDataUtils.getRandomString(10))
                                        )
                                        .withName("Name1")
                                        .withBid(30000000l)
                                        .withAdGroupId(pid)
                        ),
                expectedResult,
                expectedResult);
    }


    @Test
    @Issue("DIRECT-48987")
    @Description("Добавление двух невалидных условий")
    public void checkNumerationInErrorWithInvalidConditionsTest() {
        JavaOrPerlExpectedResult expectedResult = JavaOrPerlExpectedResult
                .java(ExpectedResult.errors(
                        new Notification(5004, Api5ErrorDetails.INVALID_FORMAT_WEBPAGE_CONDITION, 1)
                                .withDetails("Неправильный формат правила №1: задано неподдерживаемое отношение"),
                        new Notification(5004, Api5ErrorDetails.INVALID_FORMAT_WEBPAGE_CONDITION, 2)
                                .withDetails("Неправильный формат правила №2: задано неподдерживаемое отношение"))
                )
                .perl(ExpectedResult.errors(
                        new Notification(5004, Api5ErrorDetails.INVALID_FORMAT_WEBPAGE_CONDITION, 1),
                        new Notification(5004, Api5ErrorDetails.INVALID_FORMAT_WEBPAGE_CONDITION, 2))
                );
        api.userSteps.dynamicTextAdTargetsSteps().shouldGetResultOnAdd(
                new AddRequestMap()
                        .withWebpages(
                                new WebpageAddItemMap()
                                        .withConditions(
                                                new WebpageConditionMap()
                                                        .withOperand(WebpageConditionOperandEnum.PAGE_TITLE)
                                                        .withOperator(StringConditionOperatorEnum.EQUALS_ANY)
                                                        .withArguments(RandomDataUtils.getRandomString(10)),
                                                new WebpageConditionMap()
                                                        .withOperand(WebpageConditionOperandEnum.PAGE_CONTENT)
                                                        .withOperator(StringConditionOperatorEnum.NOT_EQUALS_ALL)
                                                        .withArguments(RandomDataUtils.getRandomString(10))
                                        )
                                        .withName("Name1")
                                        .withBid(30000000l)
                                        .withAdGroupId(pid)
                        ),
                expectedResult);
    }

     /*
    @Test
    public void tryAddSameWebpagesByOneRequestWithDifferentName() {
        api.userSteps.dynamicTextAdTargetsSteps().shouldGetResultOnAdd(
                new AddRequestMap().withWebpages(
                        new WebpageAddItemMap()
                                .withAdGroupId(pid)
                                .withName("Name2")
                                .withConditions(
                                        new WebpageConditionMap()
                                                .withOperand(WebpageConditionOperandEnum.URL)
                                                .withOperator(StringConditionOperatorEnum.CONTAINS_ANY)
                                                .withArguments("https://ya.ru")
                                )
                                .withBid(30000000l),
                        new WebpageAddItemMap()
                                .withAdGroupId(pid)
                                .withName("Name1")
                                .withConditions(
                                        new WebpageConditionMap()
                                                .withOperand(WebpageConditionOperandEnum.URL)
                                                .withOperator(StringConditionOperatorEnum.CONTAINS_ANY)
                                                .withArguments("https://ya.ru")
                                )
                                .withBid(30000000l)
                ),
                ExpectedResult.success(),
                ExpectedResult.errors()
        );}    */

}
