package ru.yandex.autotests.direct.api.audiencetargets.add;

import java.util.List;

import com.yandex.direct.api.v5.general.PriorityEnum;
import com.yandex.direct.api.v5.general.YesNoEnum;
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.direct.api.audiencetargets.AudienceTargetsFeatures;
import ru.yandex.autotests.direct.api.audiencetargets.AudienceTargetsLogins;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.RetargetingConditionsRetargetingConditionsType;
import ru.yandex.autotests.direct.utils.money.MoneyCurrency;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetailsJava;
import ru.yandex.autotests.directapi.model.User;
import ru.yandex.autotests.directapi.model.api5.audiencetargets.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.audiencetargets.AudienceTargetAddItemMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
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.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 static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assume.assumeThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;

/**
 * Created by ginger on 30.11.16.
 * https://st.yandex-team.ru/TESTIRT-8519
 */
@Aqua.Test
@Features(AudienceTargetsFeatures.ADD)
@Description("Общие проверки метода")
@Issue("https://st.yandex-team.ru/DIRECT-48447")
public class AddAudienceTargetsInterestsTest {
    private static final String LOGIN = AudienceTargetsLogins.LOGIN_TARGET1;
    private static Long campaignId;
    private Long adGroupId;
    private static Long isTargetableInterestId;
    private static Long isNotTargetableInterestId;

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

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

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

    private static int shard;

    @BeforeClass
    public static void prepare() {
        shard = api.userSteps.clientFakeSteps().getUserShard(LOGIN);
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(LOGIN);
        campaignId = api.userSteps.campaignSteps().addDefaultMobileAppCampaign();
        isTargetableInterestId = api.userSteps.dictionariesSteps().getInterestIdByIsTargetable(YesNoEnum.YES);
        isNotTargetableInterestId = api.userSteps.dictionariesSteps().getInterestIdByIsTargetable(YesNoEnum.NO);
    }

    @Before
    public void addAdGroup() {
        adGroupId = api.userSteps.adGroupsSteps().addDefaultMobileGroup(campaignId);
    }

    @Test
    public void successAddAudienceTargetsWithInterestWithIsTargetableYes() {
        api.userSteps.audienceTargetsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withAudienceTargets(new AudienceTargetAddItemMap()
                                .withAdGroupId(adGroupId)
                                .withInterestId(isTargetableInterestId)
                                .withContextBid(MoneyCurrency.get(User.get(LOGIN)
                                        .getCurrency()).getLongMinPrice().longValue())),
                ExpectedResult.success());
    }

    @Test
    public void successAddAudienceTargetsWithInterestAndCheckType() {
        List<Long> ids = api.userSteps.audienceTargetsSteps().add(new AddRequestMap()
                .withAudienceTargets(new AudienceTargetAddItemMap()
                        .withAdGroupId(adGroupId)
                        .withInterestId(isTargetableInterestId)
                        .withContextBid(MoneyCurrency.get(User.get(LOGIN)
                                .getCurrency()).getLongMinPrice().longValue())));
        assumeThat(ids, hasSize(1));

        RetargetingConditionsRetargetingConditionsType retargetingConditionsType =
                getRetargetingConditionsTypeForAudienceTargetId(ids);
        assertThat("ссылается на запись с правильным типом", retargetingConditionsType,
                equalTo(RetargetingConditionsRetargetingConditionsType.metrika_goals));

    }

    @Test
    public void tryAddAudienceTargetsWithInterestWithIsTargetableNo() {
        api.userSteps.audienceTargetsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withAudienceTargets(new AudienceTargetAddItemMap()
                                .withAdGroupId(adGroupId)
                                .withInterestId(isNotTargetableInterestId)
                                .withContextBid(MoneyCurrency.get(User.get(LOGIN)
                                        .getCurrency()).getLongMinPrice().longValue())),
                ExpectedResult.errors(new Notification(6000,
                        Api5ErrorDetailsJava.IN_AUDIENCE_TARGET_CAN_BE_USED_ONLY_INTEREST_IS_TARGETABLE_YES)));
    }

    @Test
    public void tryAddAudienceTargetsWithTwoSameInterestsInOneGroupOneRequest() {
        api.userSteps.audienceTargetsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withAudienceTargets(
                                new AudienceTargetAddItemMap()
                                        .withAdGroupId(adGroupId)
                                        .withInterestId(isTargetableInterestId)
                                        .withContextBid(MoneyCurrency.get(User.get(LOGIN)
                                                .getCurrency()).getLongMinPrice().longValue()),
                                new AudienceTargetAddItemMap()
                                        .withAdGroupId(adGroupId)
                                        .withInterestId(isTargetableInterestId)
                                        .withStrategyPriority(PriorityEnum.LOW)),
                // ожидаем по ошибке на каждый из дубликатов
                ExpectedResult.errors(new Notification(9800, Api5ErrorDetailsJava.RETARGETING_LISTS_UNIQUE)),
                ExpectedResult.errors(new Notification(9800, Api5ErrorDetailsJava.RETARGETING_LISTS_UNIQUE)));
    }

    @Test
    public void tryAddAudienceTargetsWithTwoSameInterestsInOneGroupTwoRequests() {
        api.userSteps.audienceTargetsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withAudienceTargets(
                                new AudienceTargetAddItemMap()
                                        .withAdGroupId(adGroupId)
                                        .withInterestId(isTargetableInterestId)
                                        .withContextBid(MoneyCurrency.get(User.get(LOGIN)
                                                .getCurrency()).getLongMinPrice().longValue())),
                ExpectedResult.success());
        api.userSteps.audienceTargetsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withAudienceTargets(
                                new AudienceTargetAddItemMap()
                                        .withAdGroupId(adGroupId)
                                        .withInterestId(isTargetableInterestId)
                                        .withStrategyPriority(PriorityEnum.LOW)),
                ExpectedResult.errors(new Notification(9801,
                        Api5ErrorDetailsJava.RETARGETING_LISTS_ALREADY_EXISTS_IN_GROUP)));
    }

    @Test
    public void successAddAudienceTargetsWithTwoSameInterestsInDiffGroups() {
        Long adGroupId2 = api.userSteps.adGroupsSteps().addDefaultMobileGroup(campaignId);
        api.userSteps.audienceTargetsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withAudienceTargets(
                                new AudienceTargetAddItemMap()
                                        .withAdGroupId(adGroupId)
                                        .withInterestId(isTargetableInterestId)
                                        .withContextBid(MoneyCurrency.get(User.get(LOGIN)
                                                .getCurrency()).getLongMinPrice().longValue()),
                                new AudienceTargetAddItemMap()
                                        .withAdGroupId(adGroupId2)
                                        .withInterestId(isTargetableInterestId)
                                        .withStrategyPriority(PriorityEnum.LOW)),
                ExpectedResult.success(), ExpectedResult.success());
    }

    private RetargetingConditionsRetargetingConditionsType getRetargetingConditionsTypeForAudienceTargetId(
            List<Long> ids)
    {
        Long retCondId = api.userSteps.getDirectJooqDbSteps().useShardForLogin(LOGIN).bidsRetargetingSteps()
                .getBidsRetargeting(ids.get(0))
                .getRetCondId();
        return api.userSteps.getDirectJooqDbSteps().useShard(shard).retargetingConditionSteps()
                .getRetargeingConditionByRetCondId(retCondId).getRetargetingConditionsType();
    }
}
