package ru.yandex.autotests.directintapi.bstransport.main.offerretargeting.parameters;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.BidsHrefParamsRecord;
import ru.yandex.autotests.direct.db.steps.BidsBaseSteps;
import ru.yandex.autotests.direct.db.steps.BidsSteps;
import ru.yandex.autotests.direct.utils.money.Currency;
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.HrefMacros;
import ru.yandex.autotests.directapi.darkside.model.RunBsTransportScriptResponse;
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.darkside.model.bslogs.clientdata.OfferRetargeting;
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.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Issue;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static java.lang.String.format;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.directintapi.bstransport.TransportTestUtils.getMapValues;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;
import static ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher.beanDiffer;

@Aqua.Test
@Tag(TagDictionary.TRUNK)
@Tag(TagDictionary.RELEASE)
@Description("Транспорт: проверка отправки в БК Params в офферном ретаргетинге")
@Features({FeatureNames.OFFER_RETARGETING})
@Issue("https://st.yandex-team.ru/DIRECT-158191")
public class OfferRetargetingParamsTest {
    private static final String LOGIN = Logins.LOGIN_TRANSPORT_IMG;
    private static final String PARAM1 = "some string 1";
    private static final String PARAM2 = "some string 2";
    private static final String HREF = format("http://test.yandex.ru/value={%s}", HrefMacros.PHRASE_ID);


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

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

    @Rule
    public Trashman trashman = new Trashman(api);

    private static int shard;
    private static BidsBaseSteps bidsBaseSteps;
    private static BidsSteps bidsSteps;

    @BeforeClass
    public static void beforeClass() {
        shard = api.userSteps.clientFakeSteps().getUserShard(LOGIN);
        bidsBaseSteps = api.userSteps.getDirectJooqDbSteps().useShard(shard).bidsBaseSteps();
        bidsSteps = api.userSteps.getDirectJooqDbSteps().useShard(shard).bidsSteps();
    }


    @Test
    public void offerRetargetingWithAllParams() {
        Long cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        Long pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        Long bid = api.userSteps.adsSteps().addAd(new AdAddItemMap()
                .withTextAd(new TextAdAddMap().defaultTextAd().withHref(HREF))
                .withAdGroupId(pid));
        Long offerRetargetingId = bidsBaseSteps.saveDefaultOfferRetargeting(cid, pid, Currency.RUB);

        BidsHrefParamsRecord bidsHrefParamsRecord = new BidsHrefParamsRecord()
                .setCid(cid)
                .setId(BigInteger.valueOf(offerRetargetingId))
                .setParam1(PARAM1)
                .setParam2(PARAM2);
        bidsSteps.saveBidsHrefParams(bidsHrefParamsRecord);

        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);

        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;
        List<OfferRetargeting> offerRetargetings = getMapValues(context != null ? context.getOfferRetargetings() : null);
        assumeThat("отправился один офферный таргетинг", offerRetargetings, hasSize(1));
        OfferRetargeting offerRetargeting = context.getOfferRetargeting(offerRetargetingId);
        assumeThat("отправился ожидаемый офферный таргетинг", offerRetargeting, notNullValue());
        Map<String, String> params = offerRetargeting.getParams();
        Map<String, String> expectedParams = new HashMap<>();
        expectedParams.put(OfferRetargeting.PARAM1, PARAM1);
        expectedParams.put(OfferRetargeting.PARAM2, PARAM2);
        expectedParams.put(OfferRetargeting.PARAM127, offerRetargetingId.toString());
        assertThat("отправились правильные параметры", params, beanDiffer(expectedParams));

    }

    @Test
    public void offerRetargetingWithBidsHrefParams() {
        Long cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        Long pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        Long bid = api.userSteps.adsSteps().addDefaultTextAd(pid);
        Long offerRetargetingId = bidsBaseSteps.saveDefaultOfferRetargeting(cid, pid, Currency.RUB);

        BidsHrefParamsRecord bidsHrefParamsRecord = new BidsHrefParamsRecord()
                .setCid(cid)
                .setId(BigInteger.valueOf(offerRetargetingId))
                .setParam1(PARAM1)
                .setParam2(PARAM2);
        bidsSteps.saveBidsHrefParams(bidsHrefParamsRecord);

        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);

        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;
        List<OfferRetargeting> offerRetargetings = getMapValues(context != null ? context.getOfferRetargetings() : null);
        assumeThat("отправился один офферный ретаргетинг", offerRetargetings, hasSize(1));
        OfferRetargeting offerRetargeting = context.getOfferRetargeting(offerRetargetingId);
        assumeThat("отправился ожидаемый офферный ретаргетинг", offerRetargeting, notNullValue());
        Map<String, String> params = offerRetargeting.getParams();
        Map<String, String> expectedParams = new HashMap<>();
        expectedParams.put(OfferRetargeting.PARAM1, PARAM1);
        expectedParams.put(OfferRetargeting.PARAM2, PARAM2);
        assertThat("отправились правильные параметры", params, beanDiffer(expectedParams));
    }

    @Test
    public void offerRetargetingWithParam127() {
        Long cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        Long pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        Long bid = api.userSteps.adsSteps().addAd(new AdAddItemMap()
                .withTextAd(new TextAdAddMap().defaultTextAd().withHref(HREF))
                .withAdGroupId(pid));
        Long offerRetargetingId = bidsBaseSteps.saveDefaultOfferRetargeting(cid, pid, Currency.RUB);
        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);

        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;
        List<OfferRetargeting> offerRetargetings = getMapValues(context != null ? context.getOfferRetargetings() : null);
        assumeThat("отправился один офферный ретаргетинг", offerRetargetings, hasSize(1));
        OfferRetargeting offerRetargeting = context.getOfferRetargeting(offerRetargetingId);
        assumeThat("отправился ожидаемый офферный ретаргетинг", offerRetargeting, notNullValue());
        Map<String, String> params = offerRetargeting.getParams();
        Map<String, String> expectedParams = new HashMap<>();
        expectedParams.put(OfferRetargeting.PARAM127, offerRetargetingId.toString());
        assertThat("отправились правильные параметры", params, beanDiffer(expectedParams));
    }
}
