package ru.yandex.autotests.directintapi.bstransport.main.campaign.actions.unarchiving.transmit;

import java.util.Map;

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.tables.records.BsExportQueueRecord;
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.bslogs.StopFlag;
import ru.yandex.autotests.directapi.darkside.model.bslogs.UpdateInfo;
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.TransportHelpSteps;
import ru.yandex.autotests.directintapi.bstransport.matchers.QueueRecordMatcher;
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.direct.utils.matchers.BeanEquals.beanEquals;
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("Транспорт: проверка отправки в БК разархивированной и запущенной кампании")
@Stories(StoriesNames.CAMPAIGN_ACTION_UNARCHIVING)
@Features({FeatureNames.CAMPAIGNS, FeatureNames.NOT_FOR_FULL_EXPORT})
public class BsTransportOfUnarchivedAndResumedCampaignTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;

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

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

    private static TransportHelpSteps helpSteps = new TransportHelpSteps(api);

    private static int shard;

    private static Long cid;

    private static Campaign campaign;
    private static Map<String, Context> contexts;

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

        cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        Long pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        Long 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.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);

        api.userSteps.campaignSteps().campaignsSuspend(cid);
        api.userSteps.getDarkSideSteps().getTransportSteps().sendSyncedCampaign(shard, cid);

        api.userSteps.getDirectJooqDbSteps().campaignsSteps().makeCampaignReadyForArchive(cid);
        api.userSteps.campaignSteps().campaignsArchive(cid);
        api.userSteps.getDarkSideSteps().getTransportSteps().sendSyncedCampaign(shard, cid);

        api.userSteps.campaignSteps().campaignsUnarchive(cid);
        api.userSteps.campaignSteps().campaignsResume(cid);

        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);

        api.userSteps.getDarkSideSteps().getTransportSteps().runBsExportMasterScript(shard, cid);
        BsExportQueueRecord campInExportQueue = api.userSteps.getDirectJooqDbSteps().useShard(shard)
                .transportSteps().getBsExportQueueRecord(cid);
        assumeThat("в таблице ppc.bs_export_queue присутствует правильная запись " +
                        "для запущенной кампании",
                campInExportQueue, new QueueRecordMatcher()
                        .withCamps()
                        .withoutPrices()
                        .withContexts()
                        .withBids()
                        .withBanners()
                        .withoutFullExport()
        );

        RunBsTransportScriptResponse resp =
                api.userSteps.getDarkSideSteps().getTransportSteps().runBsClientDataScript(shard, cid);
        campaign = api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, cid);
        contexts = campaign != null && campaign.getContexts() != null && campaign.getContexts().size() > 0 ?
                campaign.getContexts() : null;
    }

    @Test
    @Title("Отправка в БК одновременно разархивации и запуска кампании - проверка объекта Кампания")
    public void testTransportForUnarchivedAndStartedCampaignOfCampaignObj() {
        Campaign expectedCampaign = helpSteps.buildExpectedCampaignObjFromDb(cid, shard, UpdateInfo.UPDATE);
        expectedCampaign.setStop(StopFlag.RESUME.value());
        expectedCampaign.setArchive(0);
        assertThat("данные отправки разархивированной и запущенной кампании не соответствуют ожидаемым",
                campaign, beanEquals(expectedCampaign));
    }

    @Test
    @Title("Отправка в БК одновременно разархивации и запуска кампании - проверка списка Контекстов")
    public void testTransportForUnarchivedAndStartedCampaignOfContextList() {
        assertThat("вместе с разархивированной и запущенной кампанией отправлены группы",
                contexts, notNullValue());
    }
}
