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

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Arrays;
import java.util.Locale;

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.db.beans.campaign.StrategyData;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsStrategyName;
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.HrefOpeningParams;
import ru.yandex.autotests.directapi.darkside.model.RunBsTransportScriptResponse;
import ru.yandex.autotests.directapi.darkside.model.StrategyName;
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.AdUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.TextAdUpdateMap;
import ru.yandex.autotests.directapi.model.api5.ads.UpdateRequestMap;
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;

@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Title("Транспорт: проверка отправки в БК макроса в поле Href баннера")
@Stories(StoriesNames.BANNER_PARAMS_HREF)
@Features(FeatureNames.BANNERS)
@Issue("https://st.yandex-team.ru/DIRECT-155373")
@RunWith(Parameterized.class)
public class BsTransportOfHrefWithCampaignCostInUrlTest {
    private static final String LOGIN = Logins.LOGIN_TRANSPORT;
    private static Double AVG_BID = 12.34d;
    private static Double AVG_CPA = 56.70d;
    private static Double AVG_CPI = 89.00d;
    private static Double AVG_CPM = 111.10d;
    private static final String BASE_STRATEGY_DATA = new StrategyData()
            .withAvgBid(AVG_BID)
            .withAvgCpa(AVG_CPA)
            .withAvgCpi(AVG_CPI)
            .withAvgCpm(AVG_CPM)
            .toString();
    private static final String HREF = "http://test.yandex.ru/";
    private static final String PARAMS =
            "value1={" + HrefOpeningParams.CAMPAIGN_COST_TYPE + "}" +
            "&value2={" + HrefOpeningParams.CAMPAIGNCOSTTYPE + "}" +
            "&value3={" + HrefOpeningParams.CAMPAIGN_COST + "}" +
            "&value4={" + HrefOpeningParams.CAMPAIGNCOST + "}";
    private static 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 StrategyName strategyName;

    @Parameterized.Parameter(1)
    public String goalId;

    @Parameterized.Parameter(2)
    public String expectedCampaignCostType;

    @Parameterized.Parameter(3)
    public Double expectedCampaignCost;

    @Parameterized.Parameters(name = "strategyName = {0}, goalId = {1}")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new Object[][]{
            {
                StrategyName.AUTOBUDGET_AVG_CPA,
                null,
                "",
                null
            },
            {
                StrategyName.AUTOBUDGET_AVG_CPA_PER_FILTER,
                null,
                "",
                null
            },
            {
                StrategyName.AUTOBUDGET_AVG_CPA_PER_CAMP,
                null,
                "",
                null
            },
            {
                StrategyName.AUTOBUDGET_AVG_CLICK,
                null,
                "CPC",
                AVG_BID
            },
            {
                StrategyName.AUTOBUDGET_AVG_CPC_PER_FILTER,
                null,
                "CPC",
                AVG_BID
            },
            {
                StrategyName.AUTOBUDGET_AVG_CPC_PER_CAMP,
                null,
                "CPC",
                AVG_BID
            },
            {
                StrategyName.AUTOBUDGET_AVG_CPI,
                null,
                "CPI",
                AVG_CPI
            },
            {
                StrategyName.AUTOBUDGET_AVG_CPI,
                "38403095",
                "",
                null
            },
            {
                StrategyName.CPM_DEFAULT,
                null,
                "CPM",
                AVG_CPM
            },
            {
                StrategyName.AUTOBUDGET,
                null,
                "",
                null
            }
        });
    }

    @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);
        bid = api.userSteps.adsSteps().addDefaultTextAd(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);

        StrategyData strategyData = StrategyData.fromString(BASE_STRATEGY_DATA)
                .withName(CampaignsStrategyName.valueOf(strategyName.toString()));
        if (goalId != null) {
            strategyData.setGoalId(goalId);
        }
        api.userSteps.campaignFakeSteps().setStrategyName(cid.intValue(), strategyName);
        api.userSteps.campaignFakeSteps().setStrategyData(cid.intValue(), strategyData.toString());
    }

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

        Banner banner = getBannerSentToBs();
        String formattedCost = expectedCampaignCost == null
                ? ""
                : new DecimalFormat("#.##", DecimalFormatSymbols.getInstance(Locale.ENGLISH)).format(expectedCampaignCost);
        assumeThat("в БК отправлен баннер", banner, notNullValue());
        assertThat("в БК отправлен правильный макрос",
                banner.getHref(), equalTo(HREF_WITH_PARAMS
                        .replaceAll("\\{" + HrefOpeningParams.CAMPAIGN_COST_TYPE + "\\}", expectedCampaignCostType)
                        .replaceAll("\\{" + HrefOpeningParams.CAMPAIGNCOSTTYPE + "\\}", expectedCampaignCostType)
                        .replaceAll("\\{" + HrefOpeningParams.CAMPAIGN_COST + "\\}", formattedCost)
                        .replaceAll("\\{" + HrefOpeningParams.CAMPAIGNCOST + "\\}", formattedCost))
        );
    }

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

        Banner banner = getBannerSentToBs();
        String formattedCost = expectedCampaignCost == null
                ? ""
                : new DecimalFormat("#.##", DecimalFormatSymbols.getInstance(Locale.ENGLISH)).format(expectedCampaignCost);
        assumeThat("в БК отправлен баннер", banner, notNullValue());
        assertThat("в БК отправлен правильный макрос",
                banner.getHref(), equalTo(HREF_WITH_PARAMS
                        .replaceAll("\\{" + HrefOpeningParams.CAMPAIGN_COST_TYPE + "\\}", expectedCampaignCostType)
                        .replaceAll("\\{" + HrefOpeningParams.CAMPAIGNCOSTTYPE + "\\}", expectedCampaignCostType)
                        .replaceAll("\\{" + HrefOpeningParams.CAMPAIGN_COST + "\\}", formattedCost)
                        .replaceAll("\\{" + HrefOpeningParams.CAMPAIGNCOST + "\\}", formattedCost))
        );
    }

    private void updateBannerHrefAndModerate(String href) {
        api.userSteps.adsSteps()
                .adsUpdate(new UpdateRequestMap().withAds(
                        new AdUpdateItemMap()
                                .withId(bid)
                                .withTextAd(new TextAdUpdateMap().withHref(href))
                ));
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
    }

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