package ru.yandex.autotests.directintapi.bstransport.main.cpmyndxfrontpage.queue;

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

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 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.CampaignsPlatform;
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.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.tags.TestDomains;
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.qatools.Tag;
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.allure.annotations.Title;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.IsNull.notNullValue;
import static ru.yandex.autotests.directintapi.bstransport.TransportTestUtils.setBannerStatuses;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;

@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Tag(TagDictionary.TRUNK)
@Tag(TestDomains.BsTransport.EXPORT_QUEUE)
@Title("Транспорт: проверка постановки в очередь ppc.bs_export_queue нового cpm_banner'а для cpm_yndx_frontpage " +
        "кампании")
@Features({FeatureNames.CPM_YNDX_FRONTPAGE, FeatureNames.NOT_FOR_FULL_EXPORT})
@Issue("https://st.yandex-team.ru/DIRECT-85903")
@RunWith(Parameterized.class)
public class BsTransportNewBannerAddToQueueStatusModerateTest {

    // у тестового пользователя должны быть цели в Метрике
    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 int shard;
    private Long cid;
    private Long pid;
    private Long bid;
    private Long rcId;
    private Long atId;
    public TransportHelpSteps helpSteps;

    @Parameterized.Parameter()
    public String bannerStatus;
    @Parameterized.Parameter(1)
    public BannersPerformanceStatusmoderate bannersPerformanceStatusmoderate;
    @Parameterized.Parameter(2)
    public Long expected;

    @Parameterized.Parameters(name = "статус модерации баннера: {0}, " +
            "статус модерации картинки: {1}")
    public static Collection<Object[]> data() {
        Object[][] data = new Object[][]{
                {Status.NO, BannersPerformanceStatusmoderate.No, null},
                {Status.NEW, BannersPerformanceStatusmoderate.New, 0L},
                {Status.SENT, BannersPerformanceStatusmoderate.Sent, 0L},
                {Status.SENDING, BannersPerformanceStatusmoderate.Sending, 0L},
                {Status.YES, BannersPerformanceStatusmoderate.Yes, 1L},
                {Status.YES, BannersPerformanceStatusmoderate.No, 0L},
                {Status.NO, BannersPerformanceStatusmoderate.Yes, null},
        };
        return Arrays.asList(data);
    }


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

    @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);
        setBannerStatuses(api, bid, bannerStatus, bannerStatus, cid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(keywordId);
        DirectJooqDbSteps jooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShard(shard);
        helpSteps = new TransportHelpSteps(api).useDbJooqSteps(jooqDbSteps);
        jooqDbSteps.bannersPerformanceSteps()
                .setCreativeStatusModerate(cid, pid, bid, bannersPerformanceStatusmoderate);
        jooqDbSteps.perfCreativesSteps().setModerateInfo(creativeId,
                new ModerationInfo().generateTestData().toString());
        jooqDbSteps.perfCreativesSteps().setStatusModerate(creativeId, PerfCreativesStatusmoderate.Yes);

        jooqDbSteps.campaignsSteps().setPlatform(cid, CampaignsPlatform.context);
        jooqDbSteps.campaignsSteps().setType(cid,
                ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsType.cpm_yndx_frontpage);
        jooqDbSteps.campaignsSteps().setCampaignCpmYndxFrontpageAllowedTypes(cid, "frontpage");

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

    @Test
    public void testAddingToBsQueue() {
        api.userSteps.getDarkSideSteps().getTransportSteps().runBsExportMasterScript(shard, cid);
        RunBsTransportScriptResponse response = api.userSteps.transportSteps().runBsClientDataScript(shard, cid);
        if (expected == null) {
            assertThat("при попытке отправки в БК ничего не отправилось для cid = " + cid, response, nullValue());
        } else {
            Map campaign = api.userSteps.transportSteps().getRawClientDataLogRequestForCampaign(response, cid);
            assertThat("Ожидаем, что в БК может быть отправлена кампания", campaign, notNullValue());

            if (expected > 0) {
                Map context = api.userSteps.transportSteps().getRawClientDataLogRequestForContext(response, cid, pid);
                assertThat("Ожидаем, что в БК может быть отправлена группа", context, notNullValue());

                Map banner = api.userSteps.transportSteps().getRawClientDataLogRequestForBanner(response, cid, pid,
                        bid);
                assertThat("Ожидаем, что в БК может быть отправлен баннер", banner, notNullValue());
            } else {
                Map context = api.userSteps.transportSteps().getRawClientDataLogRequestForContext(response, cid, pid);
                assertThat("Ожидаем, что в БК не отправлена группа", context, nullValue());

                Map banner = api.userSteps.transportSteps().getRawClientDataLogRequestForBanner(response, cid, pid,
                        bid);
                assertThat("Ожидаем, что в БК не отправлен баннер", banner, nullValue());
            }
        }
    }
}
