package ru.yandex.autotests.direct.api.ads.add.cpmbanneradbuilderad;

import java.util.Collections;
import java.util.List;

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.ads.AdsFeatures;
import ru.yandex.autotests.direct.api.ads.AdsLogins;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannersBannerType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannersPerformanceStatusmoderate;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.BannerPixelsRecord;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.BannersPerformanceRecord;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.darkside.model.CampaignsType;
import ru.yandex.autotests.directapi.model.PixelProvider;
import ru.yandex.autotests.directapi.model.User;
import ru.yandex.autotests.directapi.model.api5.ads.AdAddItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.CpmBannerAdBuilderAdAddMap;
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.Tag;
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.Assert.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;
import static ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher.beanDiffer;

@Aqua.Test
@Features(AdsFeatures.ADD)
@Description("Проверка сохранения в БД cpm_banner")
@Issue("https://st.yandex-team.ru/DIRECT-83722")
@Tag(TagDictionary.TRUNK)
public class AddCpmBannerCheckDbTest {

    private static String LOGIN = AdsLogins.CLIENT47;
    private static String HREF = "https://ya.ru";
    private static String PIXEL = PixelProvider.YANDEXAUDIENCE.testUrl();

    @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 campaignId;
    private static Long adGroupId;
    private static Long id;
    private static DirectJooqDbSteps dbSteps;
    private static Long creativeId;

    @BeforeClass
    public static void initTest() {
        api.as(LOGIN).userSteps.clientFakeSteps().fakeClearClientSpentUnits(LOGIN);
        campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign();
        api.userSteps.campaignFakeSteps().setType(campaignId, CampaignsType.CPM_BANNER);
        adGroupId = api.userSteps.adGroupsSteps().addDefaultCpmBannerUserProfileAdGroup(campaignId);
        dbSteps = api.userSteps.getDarkSideSteps().getDirectJooqDbSteps().useShardForLogin(LOGIN);
        creativeId = dbSteps.perfCreativesSteps().saveDefaultCanvasCreativesForClient(
                Long.parseLong(User.get(LOGIN).getClientID()));
        id = api.userSteps.adsSteps().addAd(new AdAddItemMap()
                .withAdGroupId(adGroupId)
                .withCpmBannerAdBuilderAd(new CpmBannerAdBuilderAdAddMap()
                        .withCreative(creativeId)
                        .withHref(HREF)
                        .withTrackingPixels(Collections.singletonList(PIXEL))));
    }

    @Test
    public void checkTypeInBanners() {
        assertThat("объявление в БД создано с правильным типом",
                dbSteps.bannersSteps().getBanner(id).getBannerType(),
                equalTo(BannersBannerType.cpm_banner));
    }

    @Test
    public void checkCreativeInDB() {
        BannersPerformanceRecord record =
                dbSteps.bannersPerformanceSteps().getBannersPerformance(campaignId, adGroupId, id);
        BannersPerformanceRecord expectedRecord = new BannersPerformanceRecord()
                .setBid(id)
                .setCid(campaignId)
                .setPid(adGroupId)
                .setCreativeId(creativeId)
                .setStatusmoderate(BannersPerformanceStatusmoderate.New);
        assertThat("к объявлению в БД привязан правильный креатив",
                record.intoMap(), beanDiffer(expectedRecord.intoMap())
                        .useCompareStrategy(DefaultCompareStrategies.onlyExpectedFields()));
    }

    @Test
    public void checkPixelInDB() {
        List<BannerPixelsRecord> bannerPixels = dbSteps.pixelsSteps().getBannerPixelsByBid(id);
        assumeThat("к баннеру привязан один пиксель", bannerPixels, hasSize(1));
        BannerPixelsRecord expectedRecord = new BannerPixelsRecord()
                .setBid(id)
                .setPixelUrl(PIXEL);
        assertThat("к объявлению в БД привязан правильный пиксель",
                bannerPixels.get(0).intoMap(), beanDiffer(expectedRecord.intoMap())
                        .useCompareStrategy(DefaultCompareStrategies.onlyExpectedFields()));
    }
}
