package ru.yandex.autotests.directintapi.bstransport.main.performance.banner;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.cmd.rules.DirectCmdRule;
import ru.yandex.autotests.direct.cmd.rules.PerformanceBannersRule;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannersMinusGeoType;
import ru.yandex.autotests.direct.utils.model.RegionIDValues;
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.RunBsTransportScriptResponse;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Banner;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.BannerLandDataPerformance;
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.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.google.common.base.Joiner.on;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
 * Created by n-boy on 09.03.2017
 * https://st.yandex-team.ru/TESTIRT-11106
  */

@Aqua.Test
@Tag(TagDictionary.TRUNK)
@Tag(TagDictionary.RELEASE)
@Stories(StoriesNames.MINUS_GEO)
@Features(FeatureNames.SMART_BANNERS)
@Issue("https://st.yandex-team.ru/DIRECT-63267")
@Title("Отправка в БК поля Geo feed'а с в BannerLandData с учетом минус-регионов")
@RunWith(Parameterized.class)
public class BsTransportOfPerformanceWithMinusGeoBannerLandDataGeoTest {

    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 PerformanceBannersRule bannersRule = new PerformanceBannersRule().withUlogin(LOGIN);
    private static int shard;
    @Rule
    public DirectCmdRule cmdRule = DirectCmdRule.defaultRule().as(Logins.LOGIN_SUPER).withRules(bannersRule);
    @Rule
    public Trashman trashman = new Trashman(api);

    private static List adgroupGeo = Arrays.asList(String.valueOf(RegionIDValues.RUSSIA.getId()), String.valueOf(RegionIDValues.UKRAINE.getId()));

    @Parameterized.Parameter(0)
    public List<String> bannerCurrentMinusGeo;

    @Parameterized.Parameter(1)
    public List<String> resBannerLandGeo;

    private TransportHelpSteps helpSteps = new TransportHelpSteps(api);
    private Banner banner;

    @Parameterized.Parameters()
    public static Collection<Object[]> data() {
        return Arrays.asList(
                    new Object[]{Arrays.asList(String.valueOf(RegionIDValues.RUSSIA.getId())),
                                 Arrays.asList(String.valueOf(RegionIDValues.UKRAINE.getId()))},
                    new Object[]{adgroupGeo,
                                 Arrays.asList(String.valueOf(RegionIDValues.BS_MOON.getId()))}
                );
    }

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

    @Before
    @Step("Подготовка тестовых данных")
    public void before() {
        helpSteps.makePerformanceCampaignReadyForSendingToBS(bannersRule, shard);

        api.userSteps.getDirectJooqDbSteps().useShard(shard).adGroupsSteps().updatePhrases(
                api.userSteps.getDirectJooqDbSteps().useShard(shard).adGroupsSteps()
                        .getPhrases(bannersRule.getGroupId())
                        .setGeo(on(',').join(adgroupGeo))
        );
        api.userSteps.getDirectJooqDbSteps().useShard(shard).bannersSteps().saveBannersMinusGeo(
                bannersRule.getBannerId(), BannersMinusGeoType.current, StringUtils.join(bannerCurrentMinusGeo, ",")
        );

        RunBsTransportScriptResponse resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard,
                bannersRule.getCampaignId());
        Campaign campaign = api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, 0,
                bannersRule.getCampaignId());
        Context context = campaign != null ? campaign.getContext(bannersRule.getGroupId()) : null;
        banner = context != null ? context.getBanner(bannersRule.getBannerId()) : null;
        assumeThat("в БК отправлен баннер", banner, notNullValue());
    }

    @Test
    @Title("Отправка в БК BannerLandData для смарт-баннера, проверяем Geo")
    public void performanceBannerLandDataGeo() {
        assumeThat("в БК отпралено поле BannerLandData", banner.getBannerLandData(), notNullValue());
        BannerLandDataPerformance bannerLandData = new Gson().fromJson(banner.getBannerLandData()
                , BannerLandDataPerformance.class);
        assertThat("в БК на уровне BANNER отправилось поле BannerLandData с правильным Geo"
                , bannerLandData.getGeo()
                , containsInAnyOrder(resBannerLandGeo.stream().map(s -> equalTo(s)).collect(Collectors.toList())));
    }
}
