package ru.yandex.autotests.directintapi.bstransport.main.campaign.parameters.retargetingcoef;
import java.util.LinkedHashMap;
import java.util.List;

import org.hamcrest.Matchers;
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.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.model.RunBsTransportScriptResponse;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Campaign;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.ExpressionCoefs;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.BidModifierAddMap;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.RetargetingAdjustmentMap;
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.autotests.directintapi.bstransport.TransportHelpSteps;
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 com.yandex.direct.api.v5.bidmodifiers.BidModifierToggleTypeEnum.RETARGETING_ADJUSTMENT;
import static com.yandex.direct.api.v5.general.YesNoEnum.NO;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.core.IsEqual.equalTo;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

@Aqua.Test
@Tag(TagDictionary.RELEASE)
@Title("Транспорт: проверка отправки параметра RetargetingCoef на уровне кампании, выключение")
@Stories(StoriesNames.CAMPAIGN_PARAMS_RETARGETINGCOEF)
@Features({FeatureNames.CAMPAIGNS, FeatureNames.NOT_FOR_FULL_EXPORT})
@Issue("https://st.yandex-team.ru/DIRECT-42533")
public class BsTransportOfCampaignRetargetingCoefOffTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;
    private static final int COEF = 150;

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

    private static TransportHelpSteps helpSteps = new TransportHelpSteps(api);

    private static int shard;
    private static List<Long> retIds;
    private Long cid;
    private RunBsTransportScriptResponse resp;

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

    @Before
    @Step("Подготовка тестовых данных")
    public void before() {
        helpSteps.useDirectWebApiSteps(directRule.webApiSteps());
        cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);

        api.userSteps.bidModifiersSteps().bidModifiersAdd(
                new BidModifierAddMap()
                        .withCampaignId(cid)
                        .withRetargetingAdjustment(new RetargetingAdjustmentMap()
                                .withRetargetingConditionId(retIds.get(0))
                                .withBidModifier(COEF)
                        )
        );

        resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        Campaign campaign = api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, cid);
        assumeThat("отправленная в БК корректировка RetargetingCoef на уровне кампании содержит ровно одну запись",
                campaign.getRetargetingCoef().size(), equalTo(1));

        api.userSteps.bidModifiersSteps().toggleBidModifiersCampaign(cid
                , RETARGETING_ADJUSTMENT
                , NO);

        resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendCampaign(shard, cid);
    }

    @Test
    @Title("Отправка в БК корректировки RetargetingCoef на уровне кампании")
    public void testTransportOfCampaignOneRetargetingCoef() {
        assertThat("в БК отправлена корректировка RetargetingCoef со значение undef на уровне кампании",
                helpSteps.getOrderMap(resp, cid).get(Campaign.RETARGETING_COEF), Matchers.equalTo(null));

        // проверяем передачу в унифицированном формате
        Campaign campaign = api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, 0, cid);
        assumeThat("в БК отправлена кампания", campaign, notNullValue());

        ExpressionCoefs expressionCoefs = campaign.getExpressionCoefs();
        assumeThat("Отправлен ExpressionCoefs", expressionCoefs, notNullValue());

        assertThat("в БК отправлена корректировка ExpressionCoefs.Goal со значение undef на уровне кампании",
                expressionCoefs.getRetargeting(), Matchers.equalTo(null));
    }
}
