package ru.yandex.autotests.directintapi.bstransport.main.cpmbanner.transmit;

import java.util.List;
import java.util.Map;

import com.google.common.collect.ImmutableMap;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannerMeasurersMeasurerSystem;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannersPerformanceStatusmoderate;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PerfCreativesStatusmoderate;
import ru.yandex.autotests.direct.db.steps.BannerMeasurerSteps;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
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.datacontainers.jsonrpc.displaycanvas.ModerationInfo;
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.directapi.rules.Trashman;
import ru.yandex.autotests.directintapi.bstransport.FeatureNames;
import ru.yandex.autotests.irt.testutils.json.JsonUtils;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Description;
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.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;
import static ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher.beanDiffer;

@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Tag(TagDictionary.TRUNK)
@Description("Проверяем отправку в БК универсальной корректировки")
@Features(FeatureNames.CPM_BANNER)
@Issue("https://st.yandex-team.ru/DIRECT-101453")
public class SendingBannerMeasurersTest {
    private static final String LOGIN = Logins.LOGIN_TRANSPORT;

    @ClassRule
    public static ApiSteps api = new ApiSteps().as(LOGIN);
    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();
    @Rule
    public Trashman trasher = new Trashman(api);

    private static int shard;

    private Long cid;
    private Long pid;
    private Long bid;
    private DirectJooqDbSteps jooqDbSteps;

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

    @Before
    @Step("Подготовка тестовых данных")
    public void init() {
        jooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShard(shard);
        long clientId = Long.parseLong(api.userSteps.clientFakeSteps().getClientData(LOGIN).getClientID());
        Long creativeId = jooqDbSteps.perfCreativesSteps().saveDefaultCanvasCreativesForClient(clientId);

        cid = api.userSteps.campaignSteps().addDefaultCpmBannerCampaign(LOGIN);
        //создаем группу cpm-banner с ключевыми словами
        pid = api.userSteps.adGroupsSteps().addDefaultCpmBannerKeywordsAdGroup(cid);
        List<Long> keywordIds = api.userSteps.keywordsSteps().addDefaultKeywords(pid, 1);
        bid = api.userSteps.adsSteps().addDefaultCpmBannerAdBuilderAd(pid, creativeId);

        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(keywordIds.get(0));

        jooqDbSteps.bannersPerformanceSteps()
                .setCreativeStatusModerate(cid, pid, bid, BannersPerformanceStatusmoderate.Yes);
        jooqDbSteps.perfCreativesSteps().setModerateInfo(creativeId,
                new ModerationInfo().generateTestData().toString());
        jooqDbSteps.perfCreativesSteps().setStatusModerate(creativeId, PerfCreativesStatusmoderate.Yes);
    }

    @Test
    @Description("Отправка данных из banner_measurers")
    public void testBannerMeasurers() {
        String mediascopeParams = "{\"hello\":\"world\"}";
        jooqDbSteps.bannerMeasurerSteps().addBannerMeasurer(
                bid, BannerMeasurersMeasurerSystem.mediascope, mediascopeParams
        );

        Map<String, Object> measurers = sendMultiplierToBsAndGetResultMeasurers();
        assertThat("BANNER.Measurers не null", measurers, notNullValue());

        Map<Object, Object> expectedMeasurers = ImmutableMap.builder()
                .put("mediascope", JsonUtils.getObject(mediascopeParams, Map.class))
                .build();
        assertThat("BANNER.Measurers отправлен корректно", measurers, beanDiffer(expectedMeasurers));
    }

    @Test
    @Description("Отправка измерителя mediascope с параметром tnsid")
    public void testMediascopeMeasurerWithTns() {
        String mediascopeParams = "{\"hello\":\"world\",\"tnsid\":\"foobar\"}";
        jooqDbSteps.bannerMeasurerSteps().addBannerMeasurer(
                bid, BannerMeasurersMeasurerSystem.mediascope, mediascopeParams
        );

        Map<String, Object> measurers = sendMultiplierToBsAndGetResultMeasurers();
        assertThat("BANNER.Measurers не null", measurers, notNullValue());

        Map<Object, Object> expectedMeasurers = ImmutableMap.builder()
                .put("mediascope", JsonUtils.getObject(mediascopeParams, Map.class))
                .build();
        assertThat("BANNER.Measurers отправлен корректно", measurers, beanDiffer(expectedMeasurers));
    }

    @Test
    @Description("Отправка измерителя mediascope с параметром tnsid, и отдельным TNS ID на баннере")
    public void testTnsIdOverridingMediascopeMeasurerWithTns() {
        String mediascopeParams = "{\"hello\":\"world\",\"tnsid\":\"foobar\"}";
        jooqDbSteps.bannerMeasurerSteps().addBannerMeasurer(
                bid, BannerMeasurersMeasurerSystem.mediascope, mediascopeParams
        );
        jooqDbSteps.bannerMeasurerSteps().addTnsId(bid, "1234");
        String expectedMediascopeParams = "{\"hello\":\"world\",\"tnsid\":\"1234\"}";

        Map<String, Object> measurers = sendMultiplierToBsAndGetResultMeasurers();
        assertThat("BANNER.Measurers не null", measurers, notNullValue());

        Map<Object, Object> expectedMeasurers = ImmutableMap.builder()
                .put("mediascope", JsonUtils.getObject(expectedMediascopeParams, Map.class))
                .build();
        assertThat("BANNER.Measurers отправлен корректно", measurers, beanDiffer(expectedMeasurers));
    }

    @Test
    @Description("Отправка TNS ID на баннере без измерителей")
    public void testTnsIdWithoutMeasurers() {
        jooqDbSteps.bannerMeasurerSteps().addTnsId(bid, "1234");
        String expectedMediascopeParams = "{\"tnsid\":\"1234\"}";

        Map<String, Object> measurers = sendMultiplierToBsAndGetResultMeasurers();
        assertThat("BANNER.Measurers не null", measurers, notNullValue());

        Map<Object, Object> expectedMeasurers = ImmutableMap.builder()
                .put("mediascope", JsonUtils.getObject(expectedMediascopeParams, Map.class))
                .build();
        assertThat("BANNER.Measurers отправлен корректно", measurers, beanDiffer(expectedMeasurers));
    }

    @Test
    @Description("Отправка TNS ID на баннере c несколькими измерителями")
    public void testTnsIdWithSeveralMeasurers() {
        BannerMeasurerSteps bannerMeasurerSteps = jooqDbSteps.bannerMeasurerSteps();
        String mediascopeParams = "{\"hello\":\"world\"}";
        String admetricaParams = "{\"campaignId\":4,\"placementId\":4,\"creativeId\": 4,\"criteria\":\"ya\"," +
                "\"type\":\"banner\"}";
        String expectedAdmetricaParams = JsonUtils.toString((Map) JsonUtils.getObject(admetricaParams, Map.class),
                true);
        bannerMeasurerSteps.addBannerMeasurer(bid, BannerMeasurersMeasurerSystem.admetrica, admetricaParams);
        bannerMeasurerSteps.addBannerMeasurer(bid, BannerMeasurersMeasurerSystem.mediascope, mediascopeParams);
        bannerMeasurerSteps.addTnsId(bid, "1234");
        String expectedMediascopeParams = "{\"hello\":\"world\",\"tnsid\":\"1234\"}";

        Map<String, Object> measurers = sendMultiplierToBsAndGetResultMeasurers();
        assertThat("BANNER.Measurers не null", measurers, notNullValue());

        Map<Object, Object> expectedMeasurers = ImmutableMap.builder()
                .put("mediascope", JsonUtils.getObject(expectedMediascopeParams, Map.class))
                .put("admetrica", JsonUtils.getObject(expectedAdmetricaParams, Map.class))
                .build();
        assertThat("BANNER.Measurers отправлен корректно", measurers, beanDiffer(expectedMeasurers));
    }

    private Map<String, Object> sendMultiplierToBsAndGetResultMeasurers() {
        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);

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

        Campaign campaign = api.userSteps.getDarkSideSteps().getTransportSteps()
                .getClientDataRequestCampaign(resp, 0, cid);
        assumeThat("в БК отправлена кампания", campaign, notNullValue());

        Context context = campaign.getContext(pid);
        assumeThat("в БК отправлен контекст", context, notNullValue());
        Banner banner = context.getBanner(bid);
        assumeThat("в БК отправлен баннер", banner, notNullValue());

        return banner.getMeasurers();
    }
}
