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

import java.util.Arrays;

import org.junit.Before;
import org.junit.BeforeClass;
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.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.model.api5.adgroups.AdGroupAddItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.AdAddItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.TextAdAddMap;
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.StoriesNames;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Features;
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.Matchers.equalTo;
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.RELEASE)
@Title("Транспорт: проверка отправки в БК поля Href баннера с параметрами из шаблона utm меток на уровнях выше")
@Stories(StoriesNames.BANNER_PARAMS_HREF)
@Features(FeatureNames.BANNERS)
@RunWith(Parameterized.class)
public class BsTransportOfHrefWithHrefParamsOnCampaignTest {

    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);

    @Parameterized.Parameter(0)
    public String paramsOnCampaign;

    @Parameterized.Parameter(1)
    public String bannerHref;

    @Parameterized.Parameter(2)
    public String expectedHref;

    private static Long cid;
    private Long bid;
    private Long pid;
    private static int shard;

    @BeforeClass
    @Step("Подготовка данных для теста")
    public static void init() {
        shard = api.userSteps.getDarkSideSteps().getClientFakeSteps().getUserShard(LOGIN);
        cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
    }

    @Parameterized.Parameters(name = "Params on campaign {0}, href on banner {2}, expected result is {3}")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {null, "https://yandex.ru/?utm_param=val",
                        "https://yandex.ru/?utm_param=val"},
                {"utm_param2=val2", "https://yandex.ru/?utm_param=val",
                        "https://yandex.ru/?utm_param=val&utm_param2=val2"},
                {"utm_key=new_val", "https://yandex.ru/?utm_key=old_val",
                        "https://yandex.ru/?utm_key=new_val"},
        });
    }

    @Before
    @Step("Подготовка данных для теста")
    public void createBannerWithParams() {
        pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        bid = api.userSteps.adsSteps().addAd(new AdAddItemMap()
                .withTextAd(new TextAdAddMap().defaultTextAd().withHref(bannerHref))
                .withAdGroupId(pid));
        api.userSteps.getDirectJooqDbSteps().useShard(shard).campaignsSteps()
                .updateHrefParams(cid, paramsOnCampaign);

        Long keywordId = api.userSteps.keywordsSteps().addDefaultKeyword(pid);
        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(keywordId);
    }

    @Test
    @Title("Отправка поля Href баннера с шаблонами utm-параметров, заданных на уровне группы и кампании")
    public void checkBannerHrefWithParams() {
        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 banner = context != null ? context.getBanner(bid) : null;
        assumeThat("в БК отправлен баннер", banner, notNullValue());
        assertThat("в БК отправлена правильная ссылка",
                banner.getHref(), equalTo(expectedHref));
    }
}
