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

import org.junit.After;
import org.junit.Before;
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.PerfCreativesStatusmoderate;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PhrasesAdgroupType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.RetargetingConditionsRetargetingConditionsType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.RetargetingConditionsRecord;
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.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.CampaignsType;
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.GoalContext;
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.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.allure.annotations.Stories;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeThat;

@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Tag(TagDictionary.TRUNK)
@Description("Проверяем отправку сdp-сегментов условий ретаргетинга")
@Features({FeatureNames.RETARGETINGS, FeatureNames.CPM_BANNER})
@Issue("https://st.yandex-team.ru/DIRECT-129361")
@Stories(StoriesNames.RETARGETING_ACTION_CREATION)
public class SendingOfCpmBannerRetargetingCdpSegmentTest {
    private static final String CDP_SEGMENT_RET_COND_JSON =
            "[{\"goals\":[{\"goal_type\":\"cdp_segment\",\"goal_id\":2600000001,\"time\":540}," +
                    "{\"goal_type\":\"cdp_segment\",\"goal_id\":2600000002,\"time\":540}]," +
                    "\"type\":\"or\",\"interest_type\":\"null\",\"section_id\":null}]";
    private static final String EXPECTED_CDP_SEGMENT_EXPRESSION = "(2600000001:0@1018|2600000002:0@1018)";

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;

    @ClassRule
    public static DirectRule directClassRule = DirectRule.defaultClassRule();

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

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

    @Rule
    public DirectRule directRule = DirectRule.defaultRule().as(LOGIN);

    @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 DirectJooqDbSteps jooqDbSteps;
    private Long pid;
    private Campaign campaign;
    private int cdpRetId;
    private Long cdpRetCondId;

    @After
    @Step("Утилизация тестовых данных")
    public void after() {
        api.userSteps.retargetingSteps().retargetingDelete(LOGIN, cdpRetId);
        jooqDbSteps.retargetingConditionSteps().deleteRetargeingCondition(cdpRetCondId);
    }

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

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

        Long clientId =
                Long.valueOf(api.userSteps.getDarkSideSteps().getClientFakeSteps().getClientData(LOGIN).getClientID());
        cdpRetCondId = addRetargetingCondition(clientId);
        cdpRetId = api.userSteps.retargetingSteps().addRetargetingToBanner(LOGIN, bid, cdpRetCondId.intValue());

        jooqDbSteps.bannersPerformanceSteps()
                .setCreativeStatusModerate(cid, pid, bid, BannersPerformanceStatusmoderate.Yes);
        jooqDbSteps.perfCreativesSteps().setModerateInfo(creativeId,
                new ModerationInfo().generateTestData().toString());
        jooqDbSteps.perfCreativesSteps().setStatusModerate(creativeId, PerfCreativesStatusmoderate.Yes);
        api.userSteps.campaignFakeSteps().setType(cid, CampaignsType.CPM_BANNER);
        jooqDbSteps.adGroupsSteps().setType(pid, PhrasesAdgroupType.cpm_banner);
        jooqDbSteps.bannersSteps().setBannersBannerType(bid, BannersBannerType.cpm_banner);
        RunBsTransportScriptResponse resp
                = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        campaign =
                api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, 0, cid);
    }

    private Long addRetargetingCondition(Long clientId) {
        RetargetingConditionsRecord record = new RetargetingConditionsRecord()
                .setClientid(clientId)
                .setRetargetingConditionsType(RetargetingConditionsRetargetingConditionsType.metrika_goals)
                .setConditionName("Аудитория cdp-сегментов")
                .setConditionDesc(null)
                .setConditionJson(CDP_SEGMENT_RET_COND_JSON)
                .setIsDeleted(0);
        return jooqDbSteps.retargetingConditionSteps().addRetargetingCondition(record, clientId);
    }

    @Test
    public void CdpSegmentExpressionShouldIncludeSpecialBsKeyword() {
        Context context = campaign.getContext(pid);
        assumeThat("в запросе есть группа", context, notNullValue());

        final GoalContext goalContext = context.getGoalContext((long) cdpRetId);
        assumeThat("в запросе есть ретаргетинг", goalContext, notNullValue());

        assertThat("передан корректный GoalContext->{Expression}", goalContext.getExpression(),
                equalTo(EXPECTED_CDP_SEGMENT_EXPRESSION));
    }
}
