package ru.yandex.autotests.directintapi.bstransport.main.cpmprice.transmit;

import org.junit.After;
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.cmd.rules.CreativeBannerRule;
import ru.yandex.autotests.direct.cmd.rules.DirectCmdRule;
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.enums.CampaignsCpmPriceStatusApprove;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsCpmPriceStatusCorrect;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsPlatform;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PerfCreativesCreativeType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PerfCreativesStatusmoderate;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PhrasesAdgroupType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.PerfCreativesRecord;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.direct.utils.campaigns.CampaignTypeEnum;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.darkside.Logins;
import ru.yandex.autotests.directapi.darkside.connection.Semaphore;
import ru.yandex.autotests.directapi.darkside.datacontainers.jsonrpc.displaycanvas.ModerationInfo;
import ru.yandex.autotests.directapi.darkside.model.RunBsTransportScriptResponse;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Banner;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Campaign;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Context;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.directintapi.bstransport.FeatureNames;
import ru.yandex.autotests.directintapi.bstransport.TransportHelpSteps;
import ru.yandex.autotests.irt.testutils.allure.TestSteps;
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.allure.annotations.Step;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.core.IsNull.notNullValue;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher.beanDiffer;

@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Tag(TagDictionary.TRUNK)
@Description("Проверяем отправку нескольких ссылок в html5-креативах, в для cpm_price кампании")
@Features(FeatureNames.CPM_PRICE)
@Issue("https://st.yandex-team.ru/DIRECT-116830")
public class SendingCpmPriceHTML5CreativeHrefsTest {
    private static final String LOGIN = Logins.CHECK_GOALS_CLIENT;

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

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

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

    @ClassRule
    public static DirectCmdRule defaultClassRule = DirectCmdRule.defaultClassRule();

    public CreativeBannerRule bannersRule = new CreativeBannerRule(CampaignTypeEnum.TEXT).withUlogin(LOGIN);

    @Rule
    public DirectCmdRule cmdRule = DirectCmdRule.defaultRule().withRules(bannersRule);

    private static DirectJooqDbSteps directJooqDbSteps;
    private static int shard;
    private Long cid;
    private Long pid;
    private Long bid;
    private Long rcId;
    private Long atId;
    private TransportHelpSteps helpSteps;

    @BeforeClass
    public static void beforeClass() {
        directJooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShardForLogin(LOGIN);
        shard = directJooqDbSteps.getCurrentPpcShard();
    }

    @After
    @Step("Утилизация тестовых данных")
    public void after() {
        api.userSteps.audienceTargetsSteps().delete(LOGIN, atId);
        api.userSteps.retargetingListsSteps().delete(LOGIN, rcId);
    }

    @Before
    @Step("Подготовка тестовых данных")
    public void init() {
        cid = bannersRule.getCampaignId();
        Long creativeId = bannersRule.getCreativeId();
        bid = bannersRule.getBannerId();
        pid = bannersRule.getGroupId();
        Long keywordId = bannersRule.getCurrentGroup().getPhrases().get(0).getId();
        rcId = api.userSteps.retargetingListsSteps().addDefaultRetargetingLists(LOGIN);
        atId = api.userSteps.audienceTargetsSteps().addWithRetargetingList(LOGIN, pid, rcId);

        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(keywordId);
        helpSteps = new TransportHelpSteps(api).useDbJooqSteps(directJooqDbSteps);
        directJooqDbSteps.bannersPerformanceSteps()
                .setCreativeStatusModerate(cid, pid, bid, BannersPerformanceStatusmoderate.Yes);
        PerfCreativesRecord perfCreativesRecord = directJooqDbSteps.perfCreativesSteps().getPerfCreatives(creativeId);
        perfCreativesRecord
                .setCreativeType(PerfCreativesCreativeType.html5_creative)
                .setModerateInfo(new ModerationInfo().generateTestData().toString())
                .setStatusmoderate(PerfCreativesStatusmoderate.Yes)
                .setYabsData("{\"html5\": true, \"basePath\": \"https://storage.mds.yandex" +
                        ".net/get-canvas-html5-test/995356/4e19d8b6-cea2-4ec9-b930-9fd8b0747bb5/demo_html5/\"}");
        directJooqDbSteps.perfCreativesSteps().updatePerfCreatives(perfCreativesRecord);

        directJooqDbSteps.campaignsSteps().setPlatform(cid, CampaignsPlatform.search);
        directJooqDbSteps.campaignsSteps().setCampaignCpmYndxFrontpageAllowedTypes(cid, "frontpage");
        directJooqDbSteps.adGroupsSteps().addAdGroupPriority(pid, 0);
        directJooqDbSteps.perfCreativesSteps().setDefaultCpmPriceCampCreativeSize(creativeId);
        directJooqDbSteps.campaignsSteps().setCampaignCpmPriceStatuses(cid, CampaignsCpmPriceStatusApprove.Yes, CampaignsCpmPriceStatusCorrect.Yes);
        directJooqDbSteps.campaignsSteps().setType(cid, CampaignsType.cpm_price);

        directJooqDbSteps.adGroupsSteps().setType(pid, PhrasesAdgroupType.cpm_yndx_frontpage);
        directJooqDbSteps.bannersSteps().setBannersBannerType(bid, BannersBannerType.cpm_banner);

    }

    @Test
    @Description("Отправка баннера с креативом с одной  сылкой. Она берется из banners.href")
    public void testSendingToBsOneCreativeHref() {
        RunBsTransportScriptResponse resp
                = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        Campaign campaign =
                api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, 0, cid);
        Context context = campaign != null ? campaign.getContext(pid) : null;
        Banner banner = context != null ? context.getBanner(bid) : null;
        TestSteps.assumeThat("в запросе есть баннер c html5-креативом", banner, notNullValue());

        Banner expectedCanvasBanner = helpSteps.buildExpectedNewHTML5CreativeBannerFromDb(bid);

        assertThat("параметры баннера с html5-креативом соответствуют ожиданиям",
                banner,
                beanDiffer(expectedCanvasBanner).useCompareStrategy(DefaultCompareStrategies.onlyExpectedFields()));
    }

    @Test
    @Description("Отправка баннера с креативом с двумя сылками. Одна из banners.href и одна из banner_additional_hrefs")
    public void testSendingToBsTwoCreativeHrefs() {
        directJooqDbSteps.bannerAdditionalHrefSteps().addBannerAdditionalHref(bid, 0, "http://edadeal.ru");

        RunBsTransportScriptResponse resp
                = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        Campaign campaign =
                api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, 0, cid);
        Context context = campaign != null ? campaign.getContext(pid) : null;
        Banner banner = context != null ? context.getBanner(bid) : null;
        TestSteps.assumeThat("в запросе есть баннер c html5-креативом", banner, notNullValue());

        Banner expectedCanvasBanner = helpSteps.buildExpectedNewHTML5CreativeBannerFromDb(bid);

        assertThat("параметры баннера с html5-креативом соответствуют ожиданиям",
                banner,
                beanDiffer(expectedCanvasBanner).useCompareStrategy(DefaultCompareStrategies.onlyExpectedFields()));
    }

    @Test
    @Description("Отправка баннера с креативом с тремя сылками. Одна из banners.href и две из banner_additional_hrefs")
    public void testSendingToBsThreeCreativeHrefs() {
        directJooqDbSteps.bannerAdditionalHrefSteps().addBannerAdditionalHref(bid, 0, "http://edadeal.ru");
        directJooqDbSteps.bannerAdditionalHrefSteps().addBannerAdditionalHref(bid, 1, "http://taxi.yandex.ru");

        RunBsTransportScriptResponse resp
                = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        Campaign campaign =
                api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, 0, cid);
        Context context = campaign != null ? campaign.getContext(pid) : null;
        Banner banner = context != null ? context.getBanner(bid) : null;
        TestSteps.assumeThat("в запросе есть баннер c html5-креативом", banner, notNullValue());

        Banner expectedCanvasBanner = helpSteps.buildExpectedNewHTML5CreativeBannerFromDb(bid);

        assertThat("параметры баннера с html5-креативом соответствуют ожиданиям",
                banner,
                beanDiffer(expectedCanvasBanner).useCompareStrategy(DefaultCompareStrategies.onlyExpectedFields()));
    }
}
