package ru.yandex.autotests.directintapi.bstransport.main.banner.parameters.flags;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannersStatusbssynced;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PhrasesStatusbssynced;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.BannersRecord;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.PhrasesRecord;
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.ModerationFlag;
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.directintapi.bstransport.FeatureNames;
import ru.yandex.autotests.directintapi.bstransport.StoriesNames;
import ru.yandex.autotests.directintapi.bstransport.matchers.flags.AgeMatcher;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Features;
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.notNullValue;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

@Aqua.Test
@Tag(TagDictionary.TRUNK)
@Tag(TagDictionary.RELEASE)
@Title("Транспорт: проверка отправки в БК параметра Age " +
        "(возрастная метка) в различных баннерах")
@Stories(StoriesNames.BANNER_PARAMS_FLAGS)
@Features({FeatureNames.BANNERS, FeatureNames.NOT_FOR_FULL_EXPORT})
public class BsTransportOfAgeInDifferentBannersTest {

    private static final String DB_FLAGS = ModerationFlag.BABY_FOOD_8.getDbValue() + ","
            + ModerationFlag.PSEUDO_WEAPON.getDbValue() + ","
            + ModerationFlag.AGE_16.getDbValue() + ","
            + ModerationFlag.TOBACCO.getDbValue();

    private static final String login = Logins.LOGIN_TRANSPORT;

    @ClassRule
    public static ApiSteps api = new ApiSteps().as(login);

    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();

    private static int shard;

    private Long cid;
    private Long pid;
    private Long bid;

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

    @Before
    public void createAndSynchronizeBanner() {
        cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        bid = api.userSteps.adsSteps().addDefaultTextAd(pid);
        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.getDirectJooqDbSteps().useShard(shard).bannersSteps().setBannersFlags(bid, DB_FLAGS);
        api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
    }

    @Test
    @Title("Отправка в БК параметра Age (возрастная метка) в синхронизированном баннере")
    public void testTransportOfAgeInSyncedBanner() {
        PhrasesRecord phrasesRecord =
                api.userSteps.getDirectJooqDbSteps().useShard(shard).adGroupsSteps().getPhrases(pid);
        phrasesRecord.setStatusbssynced(PhrasesStatusbssynced.No);
        api.userSteps.getDirectJooqDbSteps().useShard(shard).adGroupsSteps().updatePhrases(phrasesRecord);

        RunBsTransportScriptResponse resp =
                api.userSteps.getDarkSideSteps().getTransportSteps().sendCampaign(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("параметр Age (возрастная метка) соответствует ожидаемому",
                banner.getAge(), AgeMatcher.transportAgeCompliesWithDb(DB_FLAGS));
    }

    @Test
    @Title("Отправка в БК параметра Age (возрастная метка) в отредактированном баннере")
    public void testTransportOfAgeInEditedBanner() {
        BannersRecord bannerDb = api.userSteps.getDirectJooqDbSteps().useShard(shard).bannersSteps().getBanner(bid);
        bannerDb.setStatusbssynced(BannersStatusbssynced.No);
        api.userSteps.getDirectJooqDbSteps().useShard(shard).bannersSteps().updateBanners(bannerDb);

        RunBsTransportScriptResponse resp =
                api.userSteps.getDarkSideSteps().getTransportSteps().sendCampaign(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("параметр Age (возрастная метка) соответствует ожидаемому",
                banner.getAge(), AgeMatcher.transportAgeCompliesWithDb(DB_FLAGS));
    }

    @Test
    @Title("Отправка в БК параметра Age (возрастная метка) в остановленном баннере")
    public void testTransportOfAgeInStoppedBanner() {
        api.userSteps.adsSteps().adsSuspend(bid);

        RunBsTransportScriptResponse resp =
                api.userSteps.getDarkSideSteps().getTransportSteps().sendCampaign(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("параметр Age (возрастная метка) соответствует ожидаемому",
                banner.getAge(), AgeMatcher.transportAgeCompliesWithDb(DB_FLAGS));
    }
}
