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

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

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.db.models.jooq.ppc.enums.BannersBannerType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.ImagesStatusmoderate;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PhrasesAdgroupType;
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.model.CampaignsType;
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.model.api5.campaigns.CampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignNetworkStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyAddMap;
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.StoriesNames;
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.Stories;
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;

/**
 * Created by buhter on 16/06/16.
 * https://st.yandex-team.ru/TESTIRT-9352
 */
@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Tag(TagDictionary.TRUNK)
@Tag(TestDomains.BsTransport.EXPORT_QUEUE)
@Title("Транспорт: проверка постановки в очередь ppc.bs_export_queue " +
        "нового ГО на поиске группе")
@Stories(StoriesNames.MCBANNER_ACTION_CREATION)
@Features({FeatureNames.MCBANNER, FeatureNames.NOT_FOR_FULL_EXPORT})
@Issue("https://st.yandex-team.ru/DIRECT-68242")
@RunWith(Parameterized.class)
public class BsTransportNewMcbannerAddToQueueStatusModerateTest {

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

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

    @Parameterized.Parameter()
    public String bannerStatus;
    @Parameterized.Parameter(1)
    public ImagesStatusmoderate imagesStatusmoderate;
    @Parameterized.Parameter(2)
    public Integer expected;

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


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

    @Before
    @Step("Подготовка тестовых данных")
    public void init() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(LOGIN);
        String imageHash = api.userSteps.imagesStepsV5().addImageAdAdImage(1); //240x400
        cid = api.userSteps.campaignSteps().addCampaign(
                new CampaignAddItemMap().defaultCampaignAddItem()
                        .withTextCampaign(new TextCampaignAddItemMap().defaultTextCampaign()
                                .withBiddingStrategy(new TextCampaignStrategyAddMap()
                                        .withNetwork(new TextCampaignNetworkStrategyAddMap().defaultServingOff())
                                        .withSearch(new TextCampaignSearchStrategyAddMap().defaultHighestPosition()))));
        pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        bid = api.userSteps.adsSteps().addDefaultTextImageAd(pid, imageHash);
        Long keywordId = api.userSteps.keywordsSteps().addDefaultKeyword(pid);

        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(keywordId);
        setBannerStatuses(api, bid, bannerStatus, bannerStatus, cid);
        api.userSteps.getDarkSideSteps().getDirectJooqDbSteps().useShard(shard).imagesSteps()
                .setImageStatusModerate(bid, imageHash, imagesStatusmoderate);

        api.userSteps.campaignFakeSteps().setType(cid, CampaignsType.MCBANNER);
        api.userSteps.getDirectJooqDbSteps().useShard(shard).adGroupsSteps()
                .setType(pid, PhrasesAdgroupType.mcbanner);
        api.userSteps.getDirectJooqDbSteps().useShard(shard).bannersSteps()
                .setBannersBannerType(bid, BannersBannerType.mcbanner);
    }

    @Test
    @Title("Непостановка в очередь нового ГО на поиске в новой группе")
    public void testAddingToBsQueue() {
        api.userSteps.getDarkSideSteps().getTransportSteps().runBsExportMasterScript(shard, cid);
        RunBsTransportScriptResponse response =
                api.userSteps.getDarkSideSteps().getTransportSteps().runBsClientDataScript(shard, cid);
        if (expected == null) {
            assertThat("при попытке отправки в БК ничего не отправилось", 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());
            }
        }
    }
}

