package ru.yandex.autotests.directapi.retargetinglists.update.rules;

import com.yandex.direct.api.v5.retargetinglists.RetargetingListFieldEnum;
import com.yandex.direct.api.v5.retargetinglists.RetargetingListGetItem;
import com.yandex.direct.api.v5.retargetinglists.RetargetingListRuleOperatorEnum;
import com.yandex.direct.api.v5.retargetinglists.UpdateResponse;
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.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.api5.retargetinglists.*;
import ru.yandex.autotests.directapi.model.retargeting.RetargetingGoalType;
import ru.yandex.autotests.directapi.retargetinglists.RetargetingListsFeatures;
import ru.yandex.autotests.directapi.retargetinglists.RetargetingListsLogins;
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.hazelcast.SemaphoreRule;

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

import static org.hamcrest.Matchers.*;
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 buhter on 24/02/16
 * https://st.yandex-team.ru/TESTIRT-8519
 */
@Aqua.Test
@Features(RetargetingListsFeatures.UPDATE)
@Description("Проверка диапазона значений поля MembershipLifespan")
@Issue("https://st.yandex-team.ru/DIRECT-48447")
@RunWith(Parameterized.class)
public class UpdateRetargetingListsMembershipLifespanPositiveTest {
    private static long goalId1;
    private static long goalId2;
    private static long segmentId;
    private static final String LOGIN = RetargetingListsLogins.LOGIN_RETARGETING4;
    private static List<Long> idList;

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

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

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

    @Parameterized.Parameter(0)
    public Integer lifespan;

    @Parameterized.Parameter(1)
    public Long externalId;

    @Parameterized.Parameters(name = "MembershipLifespan - {0}")
    public static Collection data() {
        prepareGoals();
        Object[][] data = new Object[][]{
                {RetargetingListRuleArgumentItemMap.MIN_MEMBERSHIP_LIFE_SPAN, goalId1},
                {RetargetingListRuleArgumentItemMap.MAX_MEMBERSHIP_LIFE_SPAN_2019, goalId1},
                {RetargetingListRuleArgumentItemMap.MAX_MEMBERSHIP_LIFE_SPAN_2019/2, goalId1},
                {RetargetingListRuleArgumentItemMap.MIN_MEMBERSHIP_LIFE_SPAN, segmentId},
                {RetargetingListRuleArgumentItemMap.MAX_MEMBERSHIP_LIFE_SPAN_2019, segmentId},
                {RetargetingListRuleArgumentItemMap.MAX_MEMBERSHIP_LIFE_SPAN_2019/2, segmentId}
        };
        return Arrays.asList(data);
    }

    public static void prepareGoals(){
        List<Long> goalIds = api.userSteps.retargetingSteps().getRetargetingGoalIDsByType(LOGIN, RetargetingGoalType.GOAL);
        assumeThat("у клиента должно быть > 1 цели", goalIds.size(), greaterThan(1));
        goalId1 = goalIds.get(0);
        goalId2 = goalIds.get(1);
        segmentId = api.userSteps.retargetingSteps().getRetargetingGoalIDsByType(LOGIN, RetargetingGoalType.SEGMENT).get(0);
    }

    @BeforeClass
    public static void prepare() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(LOGIN);
        idList = api.userSteps.retargetingListsSteps().add(new AddRequestMap()
                .withRetargetingLists(
                        new RetargetingListAddItemMap()
                                .defaultRetargetingListAddItemMap(
                                        new RetargetingListRuleArgumentItemMap()
                                                .withMembershipLifeSpan(RetargetingListRuleArgumentItemMap.DEFAULT_MEMBERSHIP_LIFE_SPAN)
                                                .withExternalId(goalId2)))
        );
        assumeThat("добавился один объект", idList, iterableWithSize(1));
    }

    @Test
    public void testValidLifespan() {
        UpdateResponse updateResponse = api.userSteps.retargetingListsSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withRetargetingLists(
                                new RetargetingListUpdateItemMap()
                                        .withId(idList.get(0))
                                        .withRules(new RetargetingListRuleItemMap()
                                                .withOperator(RetargetingListRuleOperatorEnum.ANY)
                                                .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                                        .withMembershipLifeSpan(lifespan)
                                                        .withExternalId(externalId))))
                , ExpectedResult.success());
        assumeThat("обновился 1 элемент", updateResponse.getUpdateResults(), hasSize(1));
        List<RetargetingListGetItem> listsGetItems = api.userSteps.retargetingListsSteps().get(
                new GetRequestMap()
                        .withFieldNames(
                                RetargetingListFieldEnum.ID,
                                RetargetingListFieldEnum.RULES
                        )
                        .withSelectionCriteria(
                                new RetargetingListSelectionCriteriaMap()
                                        .withIds(idList.get(0))));
        int expectedLifespan = (segmentId == externalId) ?
                RetargetingListRuleArgumentItemMap.MAX_MEMBERSHIP_LIFE_SPAN_2019 : lifespan;
        List<RetargetingListGetItem> expected = new ArrayList<>();
        expected.add((RetargetingListGetItem)
                new RetargetingListGetItemMap()
                        .withId(updateResponse.getUpdateResults().get(0).getId())
                        .withRules(
                                new RetargetingListRuleItemMap()
                                        .withOperator(RetargetingListRuleOperatorEnum.ANY)
                                        .withArgumentItems(
                                                new RetargetingListRuleArgumentItemMap()
                                                        .withExternalId(externalId)
                                                        .withMembershipLifeSpan(expectedLifespan)
                        ))
                        .getBean());
        assertThat("получен верный lifespan", listsGetItems, beanDifferV5(expected));

    }
}

