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

import java.util.Arrays;
import java.util.List;

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.cmd.rules.CreativeBannerRule;
import ru.yandex.autotests.direct.cmd.rules.DirectCmdRule;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannerTurbolandingsStatusmoderate;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannersBannerType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannersPerformanceStatusmoderate;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PerfCreativesCreativeType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PerfCreativesStatusmoderate;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PhrasesAdgroupType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.PerfCreativesRecord;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.direct.utils.campaigns.CampaignTypeEnum;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.direct.web.api.core.DirectRule;
import ru.yandex.autotests.direct.web.api.models.Condition;
import ru.yandex.autotests.direct.web.api.models.CryptaGoalWeb;
import ru.yandex.autotests.direct.web.api.models.RetargetingConditionActionResponse;
import ru.yandex.autotests.direct.web.api.models.RetargetingConditionWeb;
import ru.yandex.autotests.directapi.darkside.Logins;
import ru.yandex.autotests.directapi.darkside.connection.Semaphore;
import ru.yandex.autotests.directapi.darkside.datacontainers.jsonrpc.displaycanvas.ModerationInfo;
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.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.is;
import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;

@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Title("Транспорт: проверка подмены при отправке в БК значения поле Href на ссылку на турболендинг")
@Stories(StoriesNames.BANNER_PARAMS_HREF)
@Features(FeatureNames.BANNERS)
@Issue("https://st.yandex-team.ru/DIRECT-97356")
@RunWith(Parameterized.class)
public class BsTransportOfHrefSubstitutedWithTurbolandingUrlTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;
    private static final long AVERAGE_INCOME_CRYPTA_GOAL_ID = 2499000010L;

    @ClassRule
    public static ApiSteps api = new ApiSteps().as(LOGIN);

    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();

    @ClassRule
    public static DirectCmdRule defaultClassRule = DirectCmdRule.defaultClassRule();

    private static DirectJooqDbSteps directJooqDbSteps;
    private static int shard;

    @Rule
    public Trashman trashman = new Trashman(api);
    public CreativeBannerRule bannersRule = new CreativeBannerRule(CampaignTypeEnum.TEXT).withUlogin(LOGIN);
    @Rule
    public DirectCmdRule cmdRule = DirectCmdRule.defaultRule().withRules(bannersRule);
    @Rule
    public DirectRule directRule = DirectRule.defaultRule().as(LOGIN);

    @Parameterized.Parameter
    public PhrasesAdgroupType adgroupType;
    @Parameterized.Parameter(1)
    public boolean shouldChangeHref;

    private Long cid;
    private Long pid;
    private Long bid;
    private String turbolandingHref;
    private String bannerHref;

    @BeforeClass
    public static void beforeClass() {
        directJooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShardForLogin(LOGIN);
        shard = directJooqDbSteps.getCurrentPpcShard();
    }

    @Parameterized.Parameters(name = "{0}")
    public static Iterable<Object[]> parameters() {
        return Arrays.asList(
                new Object[]{PhrasesAdgroupType.cpm_banner, false},
                new Object[]{PhrasesAdgroupType.cpm_yndx_frontpage, false},
                new Object[]{PhrasesAdgroupType.cpm_outdoor, false},
                new Object[]{PhrasesAdgroupType.cpm_geoproduct, true}
        );
    }

    @Before
    @Step("Подготовка тестовых данных")
    public void init() {
        cid = bannersRule.getCampaignId();
        Long creativeId = bannersRule.getCreativeId();
        bid = bannersRule.getBannerId();
        pid = bannersRule.getGroupId();
        Long avgIncomeRetCondId = createSingleCryptaSegmentCond(LOGIN, AVERAGE_INCOME_CRYPTA_GOAL_ID);

        Long clientId = directJooqDbSteps.usersSteps().getUser(LOGIN).getClientid();
        long tlId = directJooqDbSteps.turboLandingsSteps().createDefaultTurbolanding(clientId);
        directJooqDbSteps.bannerTurbolandingsSteps()
                .linkTurbolandingToBanner(bid, cid, tlId, false, BannerTurbolandingsStatusmoderate.Yes);

        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.retargetingSteps().addRetargetingToBanner(LOGIN, bid, avgIncomeRetCondId.intValue());
        directJooqDbSteps.bannersPerformanceSteps()
                .setCreativeStatusModerate(cid, pid, bid, BannersPerformanceStatusmoderate.Yes);
        PerfCreativesRecord perfCreativesRecord = directJooqDbSteps.perfCreativesSteps().getPerfCreatives(creativeId);
        perfCreativesRecord
                .setCreativeType(PerfCreativesCreativeType.html5_creative)
                .setModerateInfo(new ModerationInfo().generateTestData().toString())
                .setStatusmoderate(PerfCreativesStatusmoderate.Yes)
                .setYabsData("{\"html5\": true, \"basePath\": \"https://storage.mds.yandex" +
                        ".net/get-canvas-html5-test/995356/4e19d8b6-cea2-4ec9-b930-9fd8b0747bb5/demo_html5/\"}");
        directJooqDbSteps.perfCreativesSteps().updatePerfCreatives(perfCreativesRecord);
        directJooqDbSteps.campaignsSteps().setType(cid, CampaignsType.cpm_banner);
        directJooqDbSteps.adGroupsSteps().setType(pid, adgroupType);
        directJooqDbSteps.bannersSteps().setBannersBannerType(bid, BannersBannerType.cpm_banner);

        bannerHref = directJooqDbSteps.bannersSteps().getBanner(bid).getHref();
        turbolandingHref = directJooqDbSteps.turboLandingsSteps().getTurboLanding(tlId).getHref();
    }

    @Test
    public void testSendingToBs() {
        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;
        assertThat("в запросе есть баннер c html5-креативом", banner, notNullValue());
        assertThat("был отправлен правильный Href", banner.getHref(),
                is(shouldChangeHref ? turbolandingHref : bannerHref));
    }

    @Step("Подготовка правила ретаргетинга на сегмент крипты goalID = {1} для пользователя {0}")
    private Long createSingleCryptaSegmentCond(String login, long cryptaGoalId) {
        final RetargetingConditionWeb retargetingConditionWeb =
                retCondReq(singletonList(getSingleCryptaSegmentCond(cryptaGoalId)));
        RetargetingConditionActionResponse avgIncomeResult =
                directRule.webApiSteps().retargetingSteps()
                        .createRetargetingCondition(retargetingConditionWeb, login);
        return avgIncomeResult.getId();
    }

    private Condition getSingleCryptaSegmentCond(long cryptaGoalId) {
        return new Condition()
                .withInterestType(Condition.InterestTypeEnum.ALL)
                .withGoals(singletonList(new CryptaGoalWeb()
                        .withId(cryptaGoalId)
                ))
                .withType(Condition.TypeEnum.OR); // only OR type is allowed for crypta conditions
    }

    private RetargetingConditionWeb retCondReq(List<Condition> conditions) {
        return new RetargetingConditionWeb()
                .withName("testName" + System.currentTimeMillis())
                .withDescription("testDescription")
                .withType(RetargetingConditionWeb.TypeEnum.INTERESTS)
                .withConditions(conditions);
    }
}
