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.joda.time.DateTime;
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.darkside.datacontainers.jsonrpc.fake.GroupFakeInfo;
import ru.yandex.autotests.directapi.darkside.model.Status;
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.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.irt.testutils.beandiffer2.comparestrategy.defaultcomparestrategy.DefaultCompareStrategies;
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.Matchers.not;
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;
import static ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher.beanDiffer;

/**
 * Created by pavryabov on 07.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 UpdateRetargetingListAndCheckAdGroupStatusesTest {

    private static final String LOGIN = RetargetingListsLogins.LOGIN_RETARGETING42;

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

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

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

    private static Long id;
    private static Long adGroupId;

    private static final String NAME = RandomStringUtils.randomAlphabetic(8);
    private static final String DESCRIPTION = RandomStringUtils.randomAlphabetic(8);
    private static final Integer MEMBERSHIP_LIFE_SPAN = RandomUtils.nextInt(1, 50);
    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 static String lastChange = DateTime.now().minusMinutes(5).toString("yyyy-MM-dd hh:mm:ss");


    @BeforeClass
    @Step("Подготовка данных для теста")
    public static void createAd() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(LOGIN);
        List<Long> goalIds = api.userSteps.retargetingSteps().getRetargetingGoalIDsByType(LOGIN, RetargetingGoalType.GOAL);
        assumeThat("у пользователя 2 или более целей", goalIds.size(), greaterThan(1));
        goalForCreate = goalIds.get(0);
        goalForUpdate = goalIds.get(1);
        Long campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign();
        adGroupId = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        id = api.userSteps.retargetingListsSteps().add(new AddRequestMap()
                .withRetargetingLists(new RetargetingListAddItemMap()
                        .withName(NAME)
                        .withDescription(DESCRIPTION)
                        .withRules(new RetargetingListRuleItemMap()
                                .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                        .withMembershipLifeSpan(MEMBERSHIP_LIFE_SPAN)
                                        .withExternalId(goalForCreate))
                                .withOperator(OPERATOR_FOR_CREATE)))).get(0);
        api.userSteps.audienceTargetsSteps().addWithRetargetingList(adGroupId, id);
    }

    @Before
    public void before() {
        GroupFakeInfo groupFakeInfo = api.userSteps.groupFakeSteps().getGroupParams(adGroupId);
        groupFakeInfo.setStatusBsSynced(Status.YES);
        groupFakeInfo.setLastChange(lastChange);
        groupFakeInfo.setStatusModerate(Status.YES);
        groupFakeInfo.setStatusPostModerate(Status.YES);
        api.userSteps.groupFakeSteps().updateGroupParams(groupFakeInfo);
        groupFakeInfo = api.userSteps.groupFakeSteps().getGroupParams(adGroupId);
        GroupFakeInfo expectedGroupFakeInfo = new GroupFakeInfo();
        expectedGroupFakeInfo.setLastChange(lastChange);
        expectedGroupFakeInfo.setStatusBsSynced(Status.YES);
        expectedGroupFakeInfo.setStatusModerate(Status.YES);
        expectedGroupFakeInfo.setStatusPostModerate(Status.YES);
        expectedGroupFakeInfo.setPid(adGroupId);
        assumeThat("группе установлиилсь требуемые параметры", groupFakeInfo,
                beanDiffer(expectedGroupFakeInfo).useCompareStrategy(DefaultCompareStrategies.onlyExpectedFields()));
    }

    @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(MEMBERSHIP_LIFE_SPAN + 1)))),
                ExpectedResult.success());
        GroupFakeInfo groupFakeInfo = api.userSteps.groupFakeSteps().getGroupParams(adGroupId);
        assertThat("у группы сбросился StatusBsSynced", groupFakeInfo.getStatusBsSynced(), equalTo(Status.NO));
        assertThat("у группы сбросился LastChange", groupFakeInfo.getLastChange(), not(equalTo(lastChange)));
    }

    @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(MEMBERSHIP_LIFE_SPAN)))),
                ExpectedResult.success());
        GroupFakeInfo groupFakeInfo = api.userSteps.groupFakeSteps().getGroupParams(adGroupId);
        assertThat("у группы сбросился StatusBsSynced", groupFakeInfo.getStatusBsSynced(), equalTo(Status.NO));
        assertThat("у группы сбросился LastChange", groupFakeInfo.getLastChange(), not(equalTo(lastChange)));
    }

    @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(MEMBERSHIP_LIFE_SPAN)))),
                ExpectedResult.success());
        GroupFakeInfo groupFakeInfo = api.userSteps.groupFakeSteps().getGroupParams(adGroupId);
        assertThat("у группы сбросился StatusBsSynced", groupFakeInfo.getStatusBsSynced(), equalTo(Status.NO));
        assertThat("у группы сбросился LastChange", groupFakeInfo.getLastChange(), not(equalTo(lastChange)));
    }
}
