package ru.yandex.autotests.directintapi.bstransport.main.banner.parameters.mobile;

import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;

import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.CampaignsRecord;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.MobileContentRecord;
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.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.directintapi.bstransport.MobileContentCleanupRule;
import ru.yandex.autotests.directintapi.bstransport.StoriesNames;
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 java.util.Collections.singletonList;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.directapi.darkside.model.MobileContentUtils.getDefaultMobileContent;
import static ru.yandex.autotests.directapi.model.User.get;
import static ru.yandex.autotests.directintapi.bstransport.TransportTestUtils.getDefaultBannersMobileContent;
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)
@Issue("https://st.yandex-team.ru/DIRECT-129295")
@Title("Транспорт: баннеры с типом mobile_content, поле ImpressionUrl")
@Stories(StoriesNames.BANNER_PARAMS_MOBILE_CONTENT)
@Features(FeatureNames.BANNERS)
@RunWith(Parameterized.class)
public class BsTransportOfMobileBannerImpressionUrlTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;

    private static final String CAMPAIGN_NAME = "Имя кампании";
    private static final String EXPECTED_CAMPAIGN_NAME = "%D0%98%D0%BC%D1%8F%20%D0%BA%D0%B0%D0%BC%D0%BF%D0%B0%D0%BD%D0%B8%D0%B8";

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

    @Rule
    public Trashman trasher = new Trashman(api);
    @Rule
    public MobileContentCleanupRule cleanupRule = new MobileContentCleanupRule(api);

    private static Long cid;
    private static Banner banner;

    @Parameterized.Parameter(0)
    public String impressionUrl;

    @Parameterized.Parameter(1)
    public String expectedImpressionUrl;

    @Parameterized.Parameters(name = "impressionUrl = {0}")
    public static Collection<Object[]> data() {
        Object[][] data = new Object[][]{
            {
                "view.adjust.com/impression/z5zbnp",
                "http://view.adjust.com/impression/z5zbnp?gps_adid={GOOGLE_AID_LC}&oaid={OAID_LC}&ya_click_id={TRACKID}&ip_address={CLIENTIP}&language={DEVICE_LANG}&user_agent={USER_AGENT}"
            },
            {
                "https://view.adjust.io/impression/z5zbnp",
                "https://view.adjust.io/impression/z5zbnp?gps_adid={GOOGLE_AID_LC}&oaid={OAID_LC}&ya_click_id={TRACKID}&ip_address={CLIENTIP}&language={DEVICE_LANG}&user_agent={USER_AGENT}"
            },
            {
                "https://view.adjust.com/impression/z5zbnp?key=value",
                "https://view.adjust.com/impression/z5zbnp?key=value&gps_adid={GOOGLE_AID_LC}&oaid={OAID_LC}&ya_click_id={TRACKID}&ip_address={CLIENTIP}&language={DEVICE_LANG}&user_agent={USER_AGENT}"
            },
            {
                "https://view.adj.st/impression/z5zbnp",
                "https://view.adj.st/impression/z5zbnp?adj_gps_adid={GOOGLE_AID_LC}&adj_oaid={OAID_LC}&adj_ya_click_id={TRACKID}"
            },
            {
                "https://view.adj.st/impression/z5zbnp?adj_ya_click_id={logid}",
                "https://view.adj.st/impression/z5zbnp?adj_gps_adid={GOOGLE_AID_LC}&adj_oaid={OAID_LC}&adj_ya_click_id={TRACKID}"
            },
            {
                "https://impression.appsflyer.com/id569251594",
                "https://impression.appsflyer.com/id569251594?advertising_id={GOOGLE_AID_LC}&oaid={OAID_LC}&af_c_id=%1$s&clickid={TRACKID}&pid=yandexdirect_int&af_ip={CLIENTIP}&af_lang={DEVICE_LANG}&af_ua={USER_AGENT}&c=%2$s"
            },
            {
                "https://imp.control.kochava.com/track/impression?campaign_id=qwerty12",
                "https://imp.control.kochava.com/track/impression?campaign_id=qwerty12&adid={GOOGLE_AID_LC}&android_id={ANDROID_ID_LC}"
            },
            {
                "https://trk.mail.ru/i/qwerty1234",
                "https://trk.mail.ru/i/qwerty1234?mt_gaid={GOOGLE_AID_LC}&clickId={TRACKID}&regid={TRACKID}"
            },
            {
                null,
                null
            }
        };
        return Arrays.asList(data);
    }

    @Before
    @Step("Подготовка данных")
    public void beforeClass() {
        int shard = api.userSteps.clientFakeSteps().getUserShard(LOGIN);
        MobileContentRecord sendingMobileContent
                = getDefaultMobileContent(get(LOGIN).getClientID());
        Long mobileContentId = api.userSteps.getDirectJooqDbSteps().useShard(shard)
                .mobileContentSteps().saveMobileContent(sendingMobileContent);

        cid = api.userSteps.campaignSteps().addDefaultMobileAppCampaign();
        Long pid = api.userSteps.adGroupsSteps().addDefaultMobileGroup(cid);
        Long bid = api.userSteps.adsSteps().addDefaultMobileAppAd(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);

        CampaignsRecord campaignRecord = api.userSteps.getDirectJooqDbSteps().useShard(shard).campaignsSteps().getCampaignById(cid);
        campaignRecord.setName(CAMPAIGN_NAME);
        api.userSteps.getDirectJooqDbSteps().useShard(shard).campaignsSteps().updateCampaigns(campaignRecord);

        cleanupRule.setMobileContentIds(singletonList(mobileContentId));
        cleanupRule.setPids(singletonList(pid));
        cleanupRule.setShard(shard);

        api.userSteps.getDirectJooqDbSteps().useShard(shard).mobileContentSteps()
                .updateBannersMobileContent(
                        getDefaultBannersMobileContent(bid).setImpressionUrl(impressionUrl)
                );

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

        Context context = campaign.getContext(pid);
        assumeThat("в кампании присутствует Context", context, notNullValue());

        banner = context.getBanner(bid);

        assumeThat("в контексте присутствует Banner", banner, notNullValue());
    }

    @Test
    public void testTransportOfBannerMobileImpressionUrl() {
        assertThat("при отправке баннера с типом mobile_content отправляется правильное значение ImpressionUrl"
                , banner.getImpressionUrl(), equalTo(formatExpectedLink(expectedImpressionUrl)));
    }

    private String formatExpectedLink(String expectedLink) {
        return Objects.isNull(expectedLink) ? null : String.format(expectedLink, cid, EXPECTED_CAMPAIGN_NAME);
    }
}
