package ru.yandex.autotests.directintapi.bstransport.main.imagead.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.db.models.jooq.ppc.enums.BannerImagesFormatsImageType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.ImagesStatusmoderate;
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.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.enums.AdGroupType;
import ru.yandex.autotests.directapi.enums.BannerType;
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.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;

/**
 * Created by buhter on 18/10/16.
 * https://st.yandex-team.ru/TESTIRT-10364
 */
@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Tag(TagDictionary.TRUNK)
@Title("Транспорт: проверка отправки остановки графического баннера с непромодерированной картинкой")
@Stories(StoriesNames.IMAGE_AD_BANNER_ACTION_SEND)
@Features({FeatureNames.IMAGE_ADS, FeatureNames.NOT_FOR_FULL_EXPORT})
@Issue("https://st.yandex-team.ru/DIRECT-58058")
@RunWith(Parameterized.class)
public class BsTransportStopSyncedBannerWithModeratingImageAdTest {

    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 pid;
    private Long bid;

    @Parameterized.Parameter
    public ImagesStatusmoderate statusModerate;

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

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

    @Before
    @Step("Подготовка тестовых данных")
    public void init() {
        cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        String imageHash = api.userSteps.imagesStepsV5().adImagesGetAllHashes(LOGIN).get(0);
        assumeThat("выбрана картинка правильного формата", api.userSteps.getDirectJooqDbSteps().useShard(shard)
                        .imagesSteps().getBannerImagesFormatsRecords(imageHash).getImageType(),
                equalTo(BannerImagesFormatsImageType.image_ad));
        bid = api.userSteps.adsSteps().addAdWithAdImageHash(pid, AdGroupType.BASE, BannerType.IMAGE_AD, 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);
        api.userSteps.getDarkSideSteps().getDirectJooqDbSteps().useShard(shard).imagesSteps()
                .setImageStatusModerate(bid, imageHash, ImagesStatusmoderate.Yes);
        api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);

        api.userSteps.getDarkSideSteps().getDirectJooqDbSteps().useShard(shard).imagesSteps()
                .setImageStatusModerate(bid, imageHash, statusModerate);

    }

    @Test
    @Title("Отправка остановленного графического баннера")
    public void testSendingStoppedSyncedImageAd() {
        api.userSteps.adsSteps().adsSuspend(bid);
        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
    @Title("Отправка принудительно отклоненного графического баннера")
    public void testSendingRejectedSyncedImageAd() {
        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));
    }
}

