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

import java.util.List;

import com.yandex.direct.api.v5.general.PriorityEnum;
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.tables.records.BidsRetargetingRecord;
import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.direct.utils.money.MoneyCurrency;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.darkside.model.bslogs.AutoBudgetPriority;
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.campaigns.TextCampaignNetworkStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.retargeting.RetargetingGoalType;
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.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.iterableWithSize;
import static ru.yandex.autotests.direct.db.utils.JooqRecordDifferMatcher.recordDiffer;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
 * Created by buhter on 03/03/16
 * https://st.yandex-team.ru/TESTIRT-8519
 */
@Aqua.Test
@Features(AudienceTargetsFeatures.ADD)
@Description("Проверка записи в базу")
@Issue("https://st.yandex-team.ru/DIRECT-48447")
public class AddAudienceTargetsAndVerifyDBTest {
    private static final String LOGIN = AudienceTargetsLogins.LOGIN_TARGET3;

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

    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();
    private static Long pidAuto;
    private static Long pidManual;

    @Rule
    public Trashman trashman = new Trashman(api);
    private static Long userListsId;
    private static int shard;
    private static Long cidAuto;
    private static Long cidManual;

    @BeforeClass
    public static void prepare() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(LOGIN);
        shard = api.userSteps.clientFakeSteps().getUserShard(LOGIN);
        cidAuto = api.userSteps.campaignSteps().addDefaultTextCampaignWithStrategies(
                new TextCampaignSearchStrategyAddMap().defaultAverageCpc(User.get(LOGIN).getCurrency()),
                new TextCampaignNetworkStrategyAddMap().defaultServingOff()
        );
        pidAuto = api.userSteps.adGroupsSteps().addDefaultGroup(cidAuto);
        cidManual = api.userSteps.campaignSteps().addDefaultTextCampaign();
        pidManual = api.userSteps.adGroupsSteps().addDefaultGroup(cidManual);
        Long goalId =
                api.userSteps.retargetingSteps().getRetargetingGoalIDsByType(LOGIN, RetargetingGoalType.GOAL).get(0);
        userListsId = api.userSteps.retargetingListsSteps().addDefaultRetargetingLists(goalId);
    }

    @Test
    public void testDbWithAutoStrategy() {
        List<Long> targets = api.userSteps.audienceTargetsSteps().add(new AddRequestMap()
                .withAudienceTargets(new AudienceTargetAddItemMap()
                        .withAdGroupId(pidAuto)
                        .withRetargetingListId(userListsId)
                        .withStrategyPriority(PriorityEnum.LOW)));
        assumeThat("создался один объект", targets, iterableWithSize(1));

        BidsRetargetingRecord bidsRetargeting = api.userSteps.getDirectJooqDbSteps().useShardForLogin(LOGIN)
                .bidsRetargetingSteps()
                .getBidsRetargeting(targets.get(0));

        BidsRetargetingRecord expectedBidsRetargeting = new BidsRetargetingRecord()
                .setRetId(targets.get(0))
                .setRetCondId(userListsId)
                .setBid(0L)
                .setCid(cidAuto)
                .setPriceContext(MoneyCurrency.get(Currency.RUB).getMinPrice().bigDecimalValue().setScale(2))
                .setAutobudgetpriority(Integer.getInteger(AutoBudgetPriority.LOW.apiValue()))
                .setIsSuspended(0)
                .setPid(pidAuto);
        assertThat("в базу записали верный ретаргетинг", bidsRetargeting, recordDiffer(expectedBidsRetargeting)
                .useCompareStrategy(DefaultCompareStrategies.onlyExpectedFields()));
    }

    @Test
    public void testDbWithManualStrategy() {
        List<Long> targets = api.userSteps.audienceTargetsSteps().add(new AddRequestMap()
                .withAudienceTargets(new AudienceTargetAddItemMap()
                        .withAdGroupId(pidManual)
                        .withRetargetingListId(userListsId)
                        .withContextBid(MoneyCurrency.get(Currency.RUB).getMinPrice().bidLong().longValue())));
        assumeThat("создался один объект", targets, iterableWithSize(1));

        BidsRetargetingRecord bidsRetargeting = api.userSteps.getDirectJooqDbSteps().useShardForLogin(LOGIN)
                .bidsRetargetingSteps()
                .getBidsRetargeting(targets.get(0));

        BidsRetargetingRecord expectedBidsRetargeting = new BidsRetargetingRecord()
                .setRetId(targets.get(0))
                .setRetCondId(userListsId)
                .setBid(0L)
                .setCid(cidManual)
                .setPriceContext(MoneyCurrency.get(Currency.RUB).getMinPrice().bigDecimalValue().setScale(2))
                .setAutobudgetpriority(Integer.getInteger(AutoBudgetPriority.MEDIUM.apiValue()))
                .setIsSuspended(0)
                .setPid(pidManual);
        assertThat("в базу записали верный ретаргетинг", bidsRetargeting, recordDiffer(expectedBidsRetargeting)
                .useCompareStrategy(DefaultCompareStrategies.onlyExpectedFields()));
    }

}
