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

import java.util.Arrays;
import java.util.Collection;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

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.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.Status;
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.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.allure.annotations.Title;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNull.notNullValue;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
* https://st.yandex-team.ru/DIRECT-74256
*/

@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Tag(TagDictionary.TRUNK)
@Title("проверка отправки остановки баннера в кампании cpm_deals с непромодерированным HTML5-креативом")
@Features({FeatureNames.CPM_BANNER, FeatureNames.NOT_FOR_FULL_EXPORT})
@RunWith(Parameterized.class)
public class SendingStopSyncedCpmDealsBannerWithModeratingHTML5CreativeTest {

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

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

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

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

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

    private static int shard;
    private Long cid;
    private Long pid;
    private Long bid;

    @Parameterized.Parameter
    public PerfCreativesStatusmoderate statusModerate;

    @Parameterized.Parameters(name = "статус креатива: {0}")
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {PerfCreativesStatusmoderate.Error},
                {PerfCreativesStatusmoderate.New},
                {PerfCreativesStatusmoderate.No},
                {PerfCreativesStatusmoderate.Ready},
                {PerfCreativesStatusmoderate.Sending},
                {PerfCreativesStatusmoderate.Sent},
        });
    }

    @BeforeClass
    public static void beforeClass() {
        shard = api.userSteps.clientFakeSteps().getUserShard(LOGIN);
    }

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

        DirectJooqDbSteps jooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShard(shard);
        jooqDbSteps.bannersPerformanceSteps()
                .setCreativeStatusModerate(cid, pid, bid, BannersPerformanceStatusmoderate.Yes);

        jooqDbSteps.campaignsSteps().setType(cid, CampaignsType.cpm_deals);
        jooqDbSteps.adGroupsSteps().setType(pid, PhrasesAdgroupType.cpm_banner);
        jooqDbSteps.bannersSteps().setBannersBannerType(bid, BannersBannerType.cpm_banner);
        PerfCreativesRecord perfCreativesRecord = jooqDbSteps.perfCreativesSteps().getPerfCreatives(creativeId);
        perfCreativesRecord
                .setCreativeType(PerfCreativesCreativeType.html5_creative)
                .setModerateInfo(new ModerationInfo().generateTestData().toString())
                .setStatusmoderate(PerfCreativesStatusmoderate.Yes)
                .setYabsData("{\"html5\": true, \"basePath\": \"https://ya.ru/html5/\"}");
        jooqDbSteps.perfCreativesSteps().updatePerfCreatives(perfCreativesRecord);

        api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);

        jooqDbSteps.perfCreativesSteps().setStatusModerate(creativeId, statusModerate);
    }

    @Test
    public void testSendingStoppedSyncedCpmBanner() {
        api.userSteps.bannersFakeSteps().setStatusShow(bid, Status.NO);
        api.userSteps.bannersFakeSteps().setStatusBsSynced(bid, Status.NO);
        RunBsTransportScriptResponse resp
                = api.userSteps.getDarkSideSteps().getTransportSteps().sendSyncedCampaign(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;
        assumeThat("в БК отправлен баннер", banner, notNullValue());
        assertThat("для баннера отправлен Stop=1", banner.getStop(), equalTo(1));
    }

    @Test
    public void testSendingRejectedSyncedCpmBanner() {
        api.userSteps.bannersFakeSteps().setStatusBsSynced(bid, Status.NO);
        api.userSteps.bannersFakeSteps().setStatusPostModerate(bid, Status.REJECTED);
        RunBsTransportScriptResponse resp
                = api.userSteps.getDarkSideSteps().getTransportSteps().sendSyncedCampaign(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;
        assumeThat("в БК отправлен баннер", banner, notNullValue());
        assertThat("для баннера отправлен Stop=1", banner.getStop(), equalTo(1));
    }
}
