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

import java.util.List;

import com.yandex.direct.api.v5.retargetinglists.RetargetingListRuleOperatorEnum;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;

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.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.retargetinglists.RetargetingListAddItemMap;
import ru.yandex.autotests.directapi.model.api5.retargetinglists.RetargetingListRuleArgumentItemMap;
import ru.yandex.autotests.directapi.model.api5.retargetinglists.RetargetingListRuleItemMap;
import ru.yandex.autotests.directapi.model.api5.retargetinglists.RetargetingListUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.retargetinglists.UpdateRequestMap;
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.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.hamcrest.Matchers.equalTo;
import static org.hamcrest.number.OrderingComparison.greaterThan;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
 * Created by pavryabov on 10.09.16.
 * https://st.yandex-team.ru/TESTIRT-8519
 */
@Aqua.Test
@Features(RetargetingListsFeatures.UPDATE)
@Description("Проверка ленивой переотправки кампании после изменения условия ретаргетинга, " +
        "используемого для корректировки ставок на группу")
@Issue("https://st.yandex-team.ru/DIRECT-48447")
public class UpdateRetargetingListUsedForCampaignModifierTest {
    //DIRECT-58165

    private static final String LOGIN = RetargetingListsLogins.LOGIN_RETARGETING42;

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

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

    private Long id;
    private Long campaignId;

    private static final String NAME = "Name";
    private static final String DESCRIPTION = "Description";
    private static final String STEP_MSG = "группа добавилась в очередь ленивой переотправки";
    private static final RetargetingListRuleOperatorEnum OPERATOR_FOR_CREATE = RetargetingListRuleOperatorEnum.ALL;
    private static final RetargetingListRuleOperatorEnum OPERATOR_FOR_UPDATE = RetargetingListRuleOperatorEnum.ANY;
    private static Long goalForCreate;
    private static Long goalForUpdate;

    private Integer membershipLifeSpan;

    @BeforeClass
    @Step("Подготовка данных для теста")
    public static void createAd() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(LOGIN);
        List<Long> goalIds =
                api.userSteps.retargetingSteps().getRetargetingGoalIDsByType(LOGIN, RetargetingGoalType.GOAL);
        assumeThat("у пользователя 4 или более целей", goalIds.size(), greaterThan(3));
        goalForCreate = goalIds.get(2);
        goalForUpdate = goalIds.get(3);
    }

    @Before
    public void before() {
        api.userSteps.deleteAllRetargetingListsByLogin(LOGIN);

        membershipLifeSpan = RandomUtils.nextInt(1, 90);
        campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign();
        id = api.userSteps.retargetingListsSteps().add(new AddRequestMap()
                .withRetargetingLists(new RetargetingListAddItemMap()
                        .withName(NAME + RandomStringUtils.randomAlphabetic(3))
                        .withDescription(DESCRIPTION + RandomStringUtils.randomAlphabetic(3))
                        .withRules(new RetargetingListRuleItemMap()
                                .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                        .withMembershipLifeSpan(membershipLifeSpan)
                                        .withExternalId(goalForCreate))
                                .withOperator(OPERATOR_FOR_CREATE)))).get(0);
        api.userSteps.bidModifiersSteps().addBidModifierRetargetingToCampaign(id, campaignId.intValue());
        assumeThat("кампании нет в очереди ленивой переотправки",
                api.userSteps.getDirectJooqDbSteps().useShardForLogin(LOGIN).bsResyncQueueSteps()
                        .isCidInResyncQueue(campaignId),
                equalTo(false));
        api.userSteps.campaignFakeSteps().setBSSynced(campaignId, true);
    }

    @Test
    public void updateName() {
        api.userSteps.retargetingListsSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withRetargetingLists(new RetargetingListUpdateItemMap()
                                .withId(id)
                                .withName(NAME + RandomStringUtils.randomAlphabetic(5))),
                ExpectedResult.success());
        assertThat("кампания не добавилась в очередь ленивой переотправки",
                api.userSteps.getDirectJooqDbSteps().useShardForLogin(LOGIN).bsResyncQueueSteps()
                        .isCidInResyncQueue(campaignId),
                equalTo(false));
    }

    @Test
    public void updateMembershipLifespan() {
        api.userSteps.retargetingListsSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withRetargetingLists(new RetargetingListUpdateItemMap()
                                .withId(id)
                                .withRules(new RetargetingListRuleItemMap()
                                        .withOperator(OPERATOR_FOR_CREATE)
                                        .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                                .withExternalId(goalForCreate)
                                                .withMembershipLifeSpan(membershipLifeSpan + 1)))),
                ExpectedResult.success());
        assertThat(STEP_MSG,
                api.userSteps.getDirectJooqDbSteps().useShardForLogin(LOGIN).bsResyncQueueSteps()
                        .isCidInResyncQueue(campaignId),
                equalTo(true));
    }

    @Test
    public void updateExternalId() {
        api.userSteps.retargetingListsSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withRetargetingLists(new RetargetingListUpdateItemMap()
                                .withId(id)
                                .withRules(new RetargetingListRuleItemMap()
                                        .withOperator(OPERATOR_FOR_CREATE)
                                        .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                                .withExternalId(goalForUpdate)
                                                .withMembershipLifeSpan(membershipLifeSpan)))),
                ExpectedResult.success());
        assertThat(STEP_MSG,
                api.userSteps.getDirectJooqDbSteps().useShardForLogin(LOGIN).bsResyncQueueSteps()
                        .isCidInResyncQueue(campaignId),
                equalTo(true));
    }

    @Test
    public void updateOperator() {
        api.userSteps.retargetingListsSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withRetargetingLists(new RetargetingListUpdateItemMap()
                                .withId(id)
                                .withRules(new RetargetingListRuleItemMap()
                                        .withOperator(OPERATOR_FOR_UPDATE)
                                        .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                                .withExternalId(goalForCreate)
                                                .withMembershipLifeSpan(membershipLifeSpan)))),
                ExpectedResult.success());
        assertThat(STEP_MSG,
                api.userSteps.getDirectJooqDbSteps().useShardForLogin(LOGIN).bsResyncQueueSteps()
                        .isCidInResyncQueue(campaignId),
                equalTo(true));
    }
}
