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

import java.util.List;
import java.util.Map;

import com.google.common.collect.ImmutableList;
import com.yandex.direct.api.v5.general.AgeRangeEnum;
import com.yandex.direct.api.v5.general.GenderEnum;
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.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.darkside.model.multipliers.SocdemValueAge;
import ru.yandex.autotests.directapi.darkside.model.multipliers.SocdemValueGender;
import ru.yandex.autotests.directapi.enums.AgeGroup;
import ru.yandex.autotests.directapi.enums.Gender;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.BidModifierAddMap;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.DemographicsAdjustmentMap;
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.autotests.irt.testutils.beandiffer.BeanDifferMatcher;
import ru.yandex.autotests.irt.testutils.beandiffer.matchvariation.DefaultMatchVariation;
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 org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.directapi.darkside.model.BidMultiplierUtils.socdemBsAtomAge;
import static ru.yandex.autotests.directapi.darkside.model.BidMultiplierUtils.socdemBsAtomGender;
import static ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Campaign.SOCDEM_COEF;
import static ru.yandex.autotests.directintapi.bstransport.TransportTestUtils.checkBsUnifiedMultipliers;
import static ru.yandex.autotests.directintapi.bstransport.TransportTestUtils.getDefaultSocdemCoef;
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("Транспорт: проверка отправки параметра SocdemCoef на уровне кампании, добавление")
@Stories(StoriesNames.CAMPAIGN_PARAMS_SOCDEMCOEF)
@Features({FeatureNames.CAMPAIGNS, FeatureNames.NOT_FOR_FULL_EXPORT})
@Issue("https://st.yandex-team.ru/DIRECT-42533")
public class BsTransportOfCampaignSocdemCoefAddTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;
    private static final int COEF = 150;
    private static final AgeRangeEnum AGE_GROUP = AgeRangeEnum.AGE_25_34;
    private static final GenderEnum GENDER = GenderEnum.GENDER_FEMALE;

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

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

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

    private static TransportHelpSteps helpSteps = new TransportHelpSteps(api);

    private static int shard;

    private Long cid;
    private RunBsTransportScriptResponse resp;

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

    @Before
    @Step("Подготовка тестовых данных")
    public void before() {
        cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        assumeThat("в БК отправлена корректировка SocdemCoef со значение undef на уровне кампании",
                helpSteps.getOrderMap(resp, cid).get(SOCDEM_COEF), equalTo(null));

        api.userSteps.bidModifiersSteps().bidModifiersAdd(
                new BidModifierAddMap()
                        .withCampaignId(cid)
                        .withDemographicsAdjustment(new DemographicsAdjustmentMap()
                                .withAge(AGE_GROUP)
                                .withGender(GENDER)
                                .withBidModifier(COEF)
                        )
        );

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

    @Test
    @Title("Отправка в БК корректировки SocdemCoef на уровне кампании")
    public void testTransportOfCampaignSocdemCoef() {
        Map<String, Map> expected = getDefaultSocdemCoef();
        expected.get(Gender.FEMALE.toString()).put(AgeGroup.YOUNGADULT.toString(), COEF);

        assertThat("отправленная в БК корректировка SocdemCoef на уровне кампании соответствует ожидаемой",
                helpSteps.getOrderMap(resp, cid).get(Campaign.SOCDEM_COEF)
                , BeanDifferMatcher.beanDiffer(expected).withVariation(
                        new DefaultMatchVariation()
                                .setIgnoreNullFieldsOfExpectedBean(false)
                )
        );

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

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

        List<List<DirectAtom>> expectedExpression = BidMultiplierConditionBuilder.init()
                .and(socdemBsAtomAge(SocdemValueAge.AGE_25_34))
                .and(socdemBsAtomGender(SocdemValueGender.GENDER_FEMALE))
                .build();

        List<ExpressionCoefItem> socdemCoefs = expressionCoefs.getSocdem();

        checkBsUnifiedMultipliers(socdemCoefs,
                ImmutableList.of(COEF),
                ImmutableList.of(expectedExpression));
    }
}
