package ru.yandex.autotests.directintapi.bstransport.main.banner.parameters.href;
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.CampaignsType;
import ru.yandex.autotests.directapi.darkside.model.HrefOpeningParams;
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.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.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.Matchers.notNullValue;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
 * Created by semkagtn on 29.10.15.
 * https://st.yandex-team.ru/TESTIRT-7591
 */
@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Title("Транспорт: проверка отправки в БК макроса в поле Href баннера")
@Stories(StoriesNames.BANNER_PARAMS_HREF)
@Features(FeatureNames.BANNERS)
@Issue("https://st.yandex-team.ru/DIRECT-45464")
@RunWith(Parameterized.class)
public class BsTransportOfHrefWithCampaignTypeInUrlTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;
    private static final String HREF = "http://test.yandex.ru/";
    private static final String PARAMS = "value={" + HrefOpeningParams.CAMPAIGN_TYPE + "}&value1="
            + HrefOpeningParams.CAMPAIGNTYPE;
    private static final String HREF_WITH_PARAMS = HREF + "?" + PARAMS;

    @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 bid;
    private Long pid;

    @Parameterized.Parameter(0)
    public CampaignsType campaignsType;

    @Parameterized.Parameters(name = "type in DB = {0}")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {CampaignsType.TEXT},
                {CampaignsType.MCBANNER},
                {CampaignsType.MOBILE_CONTENT},
                {CampaignsType.PERFORMANCE},
                {CampaignsType.CPM_BANNER},
                {CampaignsType.CPM_DEALS},
        });
    }

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

    @Before
    @Step("Подготовка данных для теста")
    public void createBanner() {
        cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        Long keywordId = api.userSteps.keywordsSteps().addDefaultKeyword(pid);
        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(keywordId);
    }


    @Test
    @Title("Отправка макроса в поле Href в обычном баннере")
    public void checkMacrosInBannerHref() {
        createBannerWithHrefAndSetCampaignType(HREF_WITH_PARAMS);

        Banner banner = getBannerSentToBs();
        assumeThat("в БК отправлен баннер", banner, notNullValue());
        assertThat("в БК отправлен правильный макрос",
                banner.getHref(), equalTo(HREF_WITH_PARAMS
                        .replaceAll("\\{" + HrefOpeningParams.CAMPAIGN_TYPE + "\\}", campaignsType.type())
                        .replaceAll("\\{" + HrefOpeningParams.CAMPAIGNTYPE + "\\}", campaignsType.type()))
        );
    }

    @Test
    @Title("Отправка макроса в поле Href в баннере из шаблона параметров на уровне кампании")
    public void checkMacrosInBannerHrefWithParams() {
        createBannerWithHrefAndSetCampaignType(HREF);
        api.userSteps.getDirectJooqDbSteps()
                .useShard(shard)
                .campaignsSteps().updateHrefParams(cid, PARAMS);

        Banner banner = getBannerSentToBs();
        assumeThat("в БК отправлен баннер", banner, notNullValue());
        assertThat("в БК отправлен правильный макрос",
                banner.getHref(), equalTo(HREF_WITH_PARAMS
                        .replaceAll("\\{" + HrefOpeningParams.CAMPAIGN_TYPE + "\\}", campaignsType.type())
                        .replaceAll("\\{" + HrefOpeningParams.CAMPAIGNTYPE + "\\}", campaignsType.type()))
        );
    }

    private void createBannerWithHrefAndSetCampaignType(String href) {
        bid = api.userSteps.adsSteps().addAd(new AdAddItemMap()
                .withTextAd(new TextAdAddMap().defaultTextAd().withHref(href))
                .withAdGroupId(pid));
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.campaignFakeSteps().setType(cid, campaignsType);
    }

    private Banner getBannerSentToBs() {
        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;
        return context != null ? context.getBanner(bid) : null;
    }
}
