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

import java.util.List;

import com.yandex.direct.api.v5.retargetinglists.RetargetingListRuleOperatorEnum;
import com.yandex.direct.api.v5.retargetinglists.RetargetingListTypeEnum;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
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.db.models.jooq.ppc.enums.BannersPerformanceStatusmoderate;
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.steps.DirectJooqDbSteps;
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.model.User;
import ru.yandex.autotests.directapi.model.api5.retargetinglists.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.retargetinglists.RetargetingListAddItemMap;
import ru.yandex.autotests.directapi.model.api5.retargetinglists.RetargetingListRuleArgumentItemMap;
import ru.yandex.autotests.directapi.model.api5.retargetinglists.RetargetingListRuleItemMap;
import ru.yandex.autotests.directapi.model.retargeting.RetargetingGoalType;
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 java.util.Collections.singletonList;
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("Проверяем отправку группы cpm_geoproduct")
@Features(FeatureNames.CPM_GEOPRODUCT)
@Issue("https://st.yandex-team.ru/DIRECT-92596")
public class SendingCpmGeoproductCommonFieldsTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;

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

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

    private static int shard;

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

    private Campaign campaign;
    private Long cid;
    private Long pid;
    private Long bid;
    private Long rcId;
    private Long atId;

    @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() {
        DirectJooqDbSteps jooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShard(shard);

        Long creativeId = jooqDbSteps
                .perfCreativesSteps()
                .saveDefaultCanvasCreativesForClient(Long.parseLong(User.get(LOGIN).getClientID()));

        cid = api.userSteps.campaignSteps().addDefaultCpmBannerCampaign(LOGIN);
        pid = api.userSteps.adGroupsSteps().addDefaultCpmBannerUserProfileAdGroup(cid, LOGIN);
        bid = api.userSteps.adsSteps().addDefaultCpmBannerAdBuilderAd(pid, creativeId, LOGIN);

        List<Long> goalIds = api.userSteps.retargetingSteps().getRetargetingGoalIDsByType(LOGIN, RetargetingGoalType.GOAL);
        RetargetingListAddItemMap retargetingListAddItemMap = new RetargetingListAddItemMap()
                .withType(RetargetingListTypeEnum.AUDIENCE)
                .withName("Name" + RandomStringUtils.randomAlphabetic(3))
                .withDescription("Description" + RandomStringUtils.randomAlphabetic(3))
                .withRules(new RetargetingListRuleItemMap()
                        .withArgumentItems(new RetargetingListRuleArgumentItemMap()
                                .withMembershipLifeSpan(RandomUtils.nextInt(1, 90))
                                .withExternalId(goalIds.get(0)))
                        .withOperator(RetargetingListRuleOperatorEnum.ANY));
        rcId = api.userSteps.retargetingListsSteps().add(LOGIN,
                new AddRequestMap().withRetargetingLists(retargetingListAddItemMap)
        ).get(0);
        atId = api.userSteps.audienceTargetsSteps().addWithRetargetingList(LOGIN, pid, rcId);

        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        jooqDbSteps.bannersPerformanceSteps().setCreativeStatusModerate(cid, pid, bid, BannersPerformanceStatusmoderate.Yes);
        jooqDbSteps.perfCreativesSteps().setModerateInfo(creativeId, new ModerationInfo().generateTestData().toString());
        jooqDbSteps.perfCreativesSteps().setStatusModerate(creativeId, PerfCreativesStatusmoderate.Yes);
        jooqDbSteps.adGroupsSteps().setType(pid, PhrasesAdgroupType.cpm_geoproduct);
        RunBsTransportScriptResponse resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        campaign = api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, 0, cid);
    }

    @Test
    public void testContextType() {
        Context context = campaign != null ? campaign.getContext(pid) : null;
        TestSteps.assumeThat("в запросе есть группа", context, notNullValue());
        assertThat("передан правильный Context->{Type}", context.getType(),
                equalTo(PhrasesAdgroupType.cpm_banner.getLiteral()));
    }

    @Test
    public void testTags() {
        List<String> tags = singletonList("app-metro");
        Context context = campaign.getContext(pid);
        assertThat("переданы правильные Target-теги", context.getTargetTags(), equalTo(tags));
        assertThat("переданы правильные PageGroup-теги", context.getPageGroupTags(), equalTo(tags));
    }

}
