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

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.CampaignsType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PerfCreativesCreativeType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PerfCreativesSourceMediaType;
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("Проверяем отправку поля ComposedFrom в cpm_banner'е")
@Features(FeatureNames.CPM_BANNER)
@Issue("https://st.yandex-team.ru/DIRECT-75111")
public class SendingOfCpmBannerHTML5ComposedFromPresentTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT_IMG_AD;

    @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 TransportHelpSteps helpSteps;

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

    @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();

        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)
                .setSourceMediaType(PerfCreativesSourceMediaType.png)
                .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().setType(cid, CampaignsType.cpm_banner);
        directJooqDbSteps.adGroupsSteps().setType(pid, PhrasesAdgroupType.cpm_banner);
        directJooqDbSteps.bannersSteps().setBannersBannerType(bid, BannersBannerType.cpm_banner);
    }

    @Test
    public void testSendingToBs() {
        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()));
    }
}
