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

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

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.tables.records.DynamicConditionsRecord;
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.dynamicadgroups.ConditionData;
import ru.yandex.autotests.directapi.darkside.datacontainers.jsonrpc.dynamicadgroups.TargetDataDynamic;
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.BannerLandDataDynamic;
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.irt.testutils.json.JsonUtils;
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.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
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.beandiffer.BeanDifferMatcher.beanEquivalent;

@Aqua.Test
@Tag(TagDictionary.TRUNK)
@Tag(TagDictionary.RELEASE)
@Issue("https://st.yandex-team.ru/DIRECT-45146")
@Title("Транспорт: проверка отправки в БК BannerLandData для дин. баннера c UpdateInfo=1, поле Targets" +
        ", группа синхронизирована")
@Stories(StoriesNames.DYN_BANNER_PARAMS_BANNERLAND)
@Features({FeatureNames.DYN_BANNERS, FeatureNames.NOT_FOR_FULL_EXPORT})
public class BsTransportOfBannerLandDataTargetsOnlyBannerTest {

    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 BannerLandDataDynamic bannerLandDataDynamic;
    private DynamicConditionsRecord condition;

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

    @Step("Подготовка данных для теста")
    @Before
    public void before() {
        Long cid = api.userSteps.campaignSteps().addDefaultDynamicTextCampaign();
        Long pid = api.userSteps.adGroupsSteps().addDefaultGroupDynamic(cid);
        api.userSteps.dynamicTextAdTargetsSteps().addDefaultWebpage(pid);
        Long 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.bannersFakeSteps().setStatusBsSynced(bid, Status.NO);

        RunBsTransportScriptResponse resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendCampaign(shard, cid);
        Context context
                = api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, 0, cid).getContext(pid);
        assumeThat("в БК отправлен контекст", context, notNullValue());
        assumeThat("на уровне контекста не отправляются фразы", context.getPhrases(), nullValue());

        Banner banner = context.getBanner(bid);

        assumeThat("в БК отправлен баннер", banner, notNullValue());
        assumeThat("UpdateInfo отправленного баннера " + UpdateInfo.UPDATE
                , banner.getUpdateInfo(), equalTo(UpdateInfo.UPDATE.value()));
        assumeThat("отправленное поле BannerLandData не пустое", banner.getBannerLandData(), not(isEmptyString()));

        String bannerLand = banner.getBannerLandData().replaceAll("\\\\", "");
        bannerLandDataDynamic = JsonUtils.getObject(bannerLand, BannerLandDataDynamic.class);

        condition = api.userSteps.getDirectJooqDbSteps().useShard(shard)
                .dynamicConditionsSteps()
                .getDynamicConditionByAdgroupId(pid);
    }

    @Test
    public void testBannerLandDataMultipleConditions() {
        TargetDataDynamic expectedTargetData = new TargetDataDynamic();
        expectedTargetData.setDynamicConditionId(condition.getDynCondId());
        expectedTargetData.setCondition(
                Arrays.asList(JsonUtils.getObject(condition.getConditionJson(), ConditionData[].class)));

        assertThat("отправленное в БК поле BannerLandData.Targets соответствуют ожидаемому",
                bannerLandDataDynamic.getTargets(), beanEquivalent(Collections.singletonList(expectedTargetData)));
    }
}
