package ru.yandex.autotests.directintapi.bstransport.main.campaign.parameters.retargetingcoef;

import java.util.List;

import com.google.common.collect.ImmutableList;
import com.yandex.direct.api.v5.retargetinglists.RetargetingListGetItem;
import org.hamcrest.Matchers;
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.web.api.core.DirectRule;
import ru.yandex.autotests.directapi.ApiFeatures;
import ru.yandex.autotests.directapi.darkside.Logins;
import ru.yandex.autotests.directapi.darkside.connection.Semaphore;
import ru.yandex.autotests.directapi.darkside.model.BidMultiplierConditionBuilder;
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.ExpressionCoefItem;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.ExpressionCoefs;
import ru.yandex.autotests.directapi.darkside.model.multipliers.DirectAtom;
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.StoriesNames;
import ru.yandex.autotests.directintapi.bstransport.TransportHelpSteps;
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 org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.core.IsEqual.equalTo;
import static ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Campaign.RETARGETING_COEF;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

@Aqua.Test
@Title("Транспорт: проверка отправки параметра RetargetingCoef на уровне кампании, доступность условия ретаргетинга")
@Stories(StoriesNames.CAMPAIGN_PARAMS_RETARGETINGCOEF)
@Features(ApiFeatures.NOT_REGRESSION_YET)
@Issue("https://st.yandex-team.ru/DIRECT-42533")
public class BsTransportOfCampaignRetargetingCoefGoalAccessibleTest {

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

    @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 goalId = 0;
    private Campaign campaign;

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

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

        api.userSteps.bidModifiersSteps().bidModifiersAdd(
                new BidModifierAddMap()
                        .withCampaignId(cid)
                        .withRetargetingAdjustment(new RetargetingAdjustmentMap()
                                .withRetargetingConditionId(retIds.get(RETARGETING_NUM))
                                .withBidModifier(COEF)
                        )
        );
        RetargetingListGetItem retargetingListGetItem
                = api.userSteps.retargetingListsSteps().get(retIds.get(RETARGETING_NUM)).get(0);
        goalId = retargetingListGetItem.getRules().get(0).getArguments().get(0).getExternalId();
        api.userSteps.getDirectJooqDbSteps().useShard(shard).retargetingGoalsSteps()
                .setIsAccessible(retIds.get(RETARGETING_NUM), goalId, 0);

        RunBsTransportScriptResponse resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        assumeThat("в БК отправлена корректировка RetargetingCoef со значение undef на уровне кампании",
                helpSteps.getOrderMap(resp, cid).get(RETARGETING_COEF), Matchers.equalTo(null));

        api.userSteps.getDirectJooqDbSteps().useShard(shard).retargetingGoalsSteps()
                .setIsAccessible(retIds.get(RETARGETING_NUM), goalId, 1);
        goalId = 0;
        api.userSteps.campaignFakeSteps().setBSSynced(cid.intValue(), false);

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

    @Test
    @Title("Отправка в БК корректировки RetargetingCoef на уровне кампании")
    public void testTransportOfCampaignRetargetingCoef() {
        assertThat("отправленная в БК корректировка RetargetingCoef на уровне кампании содержит ровно одну запись",
                campaign.getRetargetingCoef().size(), equalTo(1));

        // проверяем передачу в унифицированном формате
        ExpressionCoefs expressionCoefs = campaign.getExpressionCoefs();
        assumeThat("Отправлен ExpressionCoefs", expressionCoefs, notNullValue());

        List<ExpressionCoefItem> retargeringCoefs = expressionCoefs.getRetargeting();
        assumeThat("Отправлен ExpressionCoefs.Goal", retargeringCoefs, notNullValue());

        assertThat("отправленная в БК корректировка ExpressionCoefs.Goal на уровне кампании содержит ровно одну запись",
                retargeringCoefs.size(), equalTo(1));
    }

    @After
    public void after(){
        if(goalId != 0) {
            api.userSteps.getDirectJooqDbSteps().useShard(shard).retargetingGoalsSteps()
                    .setIsAccessible(retIds.get(RETARGETING_NUM), goalId, 1);
        }
    }


}
