package ru.yandex.autotests.directintapi.bstransport.main.dynbanner.parameters.stop;

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.enums.BannersStatusshow;
import ru.yandex.autotests.direct.utils.matchers.BeanEquals;
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.UpdateInfo;
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.ClientDataStdLogEntry;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.ClientDataStdRequest;
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.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.is;
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("Транспорт: проверка отправки в БК обязательных полей вместе с остановкой баннера")
@Stories(StoriesNames.DYN_BANNER_PARAMS_STOP)
@Features({FeatureNames.DYN_BANNERS, FeatureNames.NOT_FOR_FULL_EXPORT})
public class BsTransportOfFieldsOfStoppingTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;
    private static final String PARAM_AGE = "Age";

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

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

    private static TransportHelpSteps helpSteps = new TransportHelpSteps(api);

    private static int shard;

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

    private static RunBsTransportScriptResponse resp;

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

        cid = api.userSteps.campaignSteps().addDefaultDynamicTextCampaign();
        pid = api.userSteps.adGroupsSteps().addDefaultGroupDynamic(cid);
        api.userSteps.dynamicTextAdTargetsSteps().addDefaultWebpage(pid);
        bid = api.userSteps.adsSteps().addDefaultDynamicTextAd(pid);

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

        api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);

        api.userSteps.getDirectJooqDbSteps().useShard(shard).bannersSteps()
                .setBannerStatusShow(bid, BannersStatusshow.No);
        api.userSteps.getDarkSideSteps().getBannersFakeSteps().setStatusBsSynced(bid, Status.NO);

        resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendCampaign(shard, cid);
    }

    @Test
    @Title("Отправка в БК обязательных полей вместе с остановкой баннера")
    public void testStoppingFields() {
        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());

        Banner expectedBanner = helpSteps.buildExpectedBannerObjFromDb(bid, shard, UpdateInfo.SKIP);
        expectedBanner.setStop(1);
        expectedBanner.setArchive(0);
        expectedBanner.setFlags("");
        BeanEquals matcher = BeanEquals.beanEquals(expectedBanner);
        assertThat("обязательные поля дин. баннера отправлены вместе с остановкой", banner, matcher);
    }

    @Test
    @Title("Отправка в БК поля Age вместе с остановкой баннера")
    public void testAgeFieldExistenceWithStopping() {
        Map<String, Map> logs =
                api.userSteps.getDarkSideSteps().getTransportSteps().getRawClientDataLogEntriesForCampaign(resp, cid);

        // достаем сырой баннер из первого запроса
        Map<String, Map> logEntry = logs.get(resp.getUuid()[0]);
        Map<String, Map> request = logEntry != null ?
                logEntry.get(ClientDataStdLogEntry.REQUEST) : null;
        Map<String, Map> orders = request != null ?
                request.get(ClientDataStdRequest.ORDERS) : null;
        Map<String, Map> order = orders != null ?
                orders.get("" + cid) : null;
        Map<String, Map> contexts = order != null ?
                order.get(Campaign.CONTEXTS) : null;
        Map<String, Map> context = contexts != null ?
                contexts.get("" + pid) : null;
        Map<String, Map> banners = context != null ?
                context.get(Context.BANNERS) : null;
        Map<String, Object> banner = banners != null ?
                banners.get("" + bid) : null;
        assumeThat("баннер отправлен в БК", banner, notNullValue());

        assertThat("поле Age отправлено вместе с остановкой дин. баннера",
                banner.keySet().contains(PARAM_AGE), is(true));
    }
}
