package ru.yandex.autotests.directintapi.bstransport.main.cpmprice.transmit;

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

import org.junit.After;
import org.junit.Before;
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.cmd.rules.CreativeBannerRule;
import ru.yandex.autotests.direct.cmd.rules.DirectCmdRule;
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.CampaignsCpmPriceStatusApprove;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsCpmPriceStatusCorrect;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsPlatform;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.CampaignsType;
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.CampOptionsRecord;
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.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.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.irt.testutils.allure.TestSteps;
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.allure.annotations.Step;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.core.IsNull.notNullValue;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;

@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Tag(TagDictionary.TRUNK)
@Description("Проверяем отправку поля PageID")
@Features(FeatureNames.CPM_PRICE)
@Issue("https://st.yandex-team.ru/DIRECT-124219")
public class SendingCpmPriceOrderPageIdTest {
    private static final String LOGIN = Logins.CHECK_GOALS_CLIENT;

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

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

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

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

    public CreativeBannerRule bannersRule = new CreativeBannerRule(CampaignTypeEnum.TEXT).withUlogin(LOGIN);

    @Rule
    public DirectCmdRule cmdRule = DirectCmdRule.defaultRule().withRules(bannersRule);

    private static int shard;
    private Long cid;
    private Long pid;
    private Long rcId;
    private Long atId;
    private Campaign campaign;
    private DirectJooqDbSteps jooqDbSteps;

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

    @After
    @Step("Утилизация тестовых данных")
    public void after() {
        api.userSteps.audienceTargetsSteps().delete(LOGIN, atId);
        api.userSteps.retargetingListsSteps().delete(LOGIN, rcId);
    }

    @Before
    @Step("Подготовка тестовых данных")
    public void init() {
        shard = api.userSteps.clientFakeSteps().getUserShard(LOGIN);
        cid = bannersRule.getCampaignId();
        Long creativeId = bannersRule.getCreativeId();
        Long bid = bannersRule.getBannerId();
        pid = bannersRule.getGroupId();
        Long keywordId = bannersRule.getCurrentGroup().getPhrases().get(0).getId();
        rcId = api.userSteps.retargetingListsSteps().addDefaultRetargetingLists(LOGIN);
        atId = api.userSteps.audienceTargetsSteps().addWithRetargetingList(LOGIN, pid, rcId);

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

        jooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShard(shard);
        jooqDbSteps.bannersPerformanceSteps()
                .setCreativeStatusModerate(cid, pid, bid, BannersPerformanceStatusmoderate.Yes);
        jooqDbSteps.perfCreativesSteps().setModerateInfo(creativeId,
                new ModerationInfo().generateTestData().toString());
        jooqDbSteps.perfCreativesSteps().setStatusModerate(creativeId, PerfCreativesStatusmoderate.Yes);

        jooqDbSteps.campaignsSteps().setPlatform(cid, CampaignsPlatform.search);
        jooqDbSteps.adGroupsSteps().addAdGroupPriority(pid, 0);
        jooqDbSteps.perfCreativesSteps().setDefaultCpmPriceCampCreativeSize(creativeId);
        jooqDbSteps.campaignsSteps().setCampaignCpmPriceStatuses(cid, CampaignsCpmPriceStatusApprove.Yes, CampaignsCpmPriceStatusCorrect.Yes);
        jooqDbSteps.campaignsSteps().setType(cid, CampaignsType.cpm_price);

        jooqDbSteps.adGroupsSteps().setType(pid, PhrasesAdgroupType.cpm_yndx_frontpage);
        jooqDbSteps.bannersSteps().setBannersBannerType(bid, BannersBannerType.cpm_banner);

    }

    @Test
    public void testAllowedFrontpageTypes() {
        jooqDbSteps.campaignsSteps().setCampaignCpmYndxFrontpageAllowedTypes(cid, "frontpage,frontpage_mobile");
        RunBsTransportScriptResponse resp
                = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        campaign =
                api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, 0, cid);
        assertThat("PageID содержит значение из allowed_frontpage_types",
                campaign.getShowCondition().getPageID(), containsInAnyOrder(
                        //DESKTOP
                        345620, 674114, 1638690, 1638708, 1654537,
                        //MOBILE
                        349254, 674124, 1638693, 1638711, 1654534, 1654540
                ));
    }

    @Test
    public void testAllowedPageIds() {
        List<Integer> testPageIds = Arrays.asList(31411, 363534);
        String testPageIdsStr = "[31411,363534]";
        CampOptionsRecord campOptions = api.userSteps.getDirectJooqDbSteps().campaignsSteps().getCampOptionsById(cid);
        campOptions.setAllowedPageIds(testPageIdsStr);
        api.userSteps.getDirectJooqDbSteps().campaignsSteps().updateCampOptions(campOptions);
        RunBsTransportScriptResponse resp
                = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        campaign =
                api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, 0, cid);
        assertThat("PageID содержит значение из allowed_page_ids",
                campaign.getShowCondition().getPageID(), equalTo(testPageIds));
    }

    @Test
    public void testMergeFrontpageAndAllowedPageIds() {
        String testPageIdsStr = "[31411,363534,345620]";
        jooqDbSteps.campaignsSteps().setCampaignCpmYndxFrontpageAllowedTypes(cid, "frontpage,frontpage_mobile");
        CampOptionsRecord campOptions = api.userSteps.getDirectJooqDbSteps().campaignsSteps().getCampOptionsById(cid);
        campOptions.setAllowedPageIds(testPageIdsStr);
        api.userSteps.getDirectJooqDbSteps().campaignsSteps().updateCampOptions(campOptions);
        RunBsTransportScriptResponse resp
                = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        campaign =
                api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, 0, cid);
        assertThat("PageID содержит значение из allowed_page_ids",
                campaign.getShowCondition().getPageID(), containsInAnyOrder(
                        // custom
                        31411, 363534,
                        //DESKTOP
                        345620, 674114, 1638690, 1638708, 1654537,
                        //MOBILE
                        349254, 674124, 1638693, 1638711, 1654534, 1654540));
    }
}
