package ru.yandex.autotests.directintapi.bstransport.main.performance.banner;

import com.google.gson.Gson;
import org.junit.After;
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.BannersBannerType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.FeedsBusinessType;
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.clientdata.Banner;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.BannerLandDataFilter;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.BannerLandDataPerformance;
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.model.User;
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.beandiffer2.beanfield.BeanFieldPath;
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.Title;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.directapi.matchers.beandiffer2.Api5CompareStrategies.onlyExpectedFields;
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.TRUNK)
@Tag(TagDictionary.RELEASE)
@Issue("https://st.yandex-team.ru/DIRECT-158191")
@Title("Транспорт: проверка отправки в БК BannerLandData фида для смарт баннера в текстовой группе")
@Features(FeatureNames.SMART_BANNERS)
public class BsTransportOfTGOFeedPerformanceBannerLandDataFeedTest {
    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;

    @Rule
    public Trashman trashman = new Trashman(api);

    private Banner banner;
    private long feedId;

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

    @Before
    @Step("Подготовка тестовых данных")
    public void before() {
        Long cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        Long pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        Long bid = api.userSteps.adsSteps().addDefaultTextAd(pid);
        api.userSteps.getDirectJooqDbSteps().useShard(shard).bannersSteps()
                .setBannersBannerType(bid, BannersBannerType.performance_main);
        Long keywordId = api.userSteps.keywordsSteps().addDefaultKeyword(pid);
        feedId = api.userSteps.getDirectJooqDbSteps().useShard(shard).feedsSteps()
                .createDefaultFeed(User.get(LOGIN).getClientID());
        api.userSteps.getDirectJooqDbSteps().useShard(shard).feedsSteps()
                .updateFeedLogin(feedId, User.get(LOGIN).getClientID(), "login");

        api.userSteps.getDirectJooqDbSteps().useShard(shard).adGroupsSteps()
                .setAdgroupsTextFeedIdAndFilter(pid, feedId, "{}");
        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(keywordId);

        RunBsTransportScriptResponse resp = api.userSteps.getDarkSideSteps().getTransportSteps()
                .sendNewCampaign(shard, cid);
        Campaign campaign = api.userSteps.getDarkSideSteps().getTransportSteps()
                .getClientDataRequestCampaign(resp, 0, cid);
        Context context = campaign != null ? campaign.getContext(pid) : null;
        banner = context != null ? context.getBanner(bid) : null;
        assumeThat("в БК отправлен баннер", banner, notNullValue());
    }

    @Test
    @Title("Отправка в БК BannerLandData для смарт баннера")
    public void testBannerLandData() {
        assumeThat("в БК отпралено поле BannerLandData", banner.getBannerLandData(), notNullValue());
        BannerLandDataPerformance bannerLandData = new Gson().fromJson(banner.getBannerLandData()
                , BannerLandDataPerformance.class);
        BannerLandDataPerformance expectedBannerLandData = new BannerLandDataPerformance();
        expectedBannerLandData.setFilter(new BannerLandDataFilter());
        expectedBannerLandData.setHrefParams("");
        expectedBannerLandData.setFeedUrl("https://yandex.st/market-export/1.0-17/partner/help/YML.xml");
        expectedBannerLandData.setLogin("login");
        expectedBannerLandData.setFeedsBusinessType(FeedsBusinessType.retail);

        assertThat("в БК на уровне BANNER отправилось поле BannerLandData с правильными данными"
                , bannerLandData
                , beanDiffer(expectedBannerLandData).useCompareStrategy(onlyExpectedFields()
                        .forFields(BeanFieldPath.newPath("substituteURLParams"))
                        .useMatcher(notNullValue())));
    }

    @After
    public void clearFeed() {
        if (feedId > 0) {
            api.userSteps.getDirectJooqDbSteps().useShard(shard).feedsSteps().deleteFeedAndAllLinksByFeedId(feedId);
        }
    }
}
