package ru.yandex.autotests.directintapi.bstransport.main.banner.parameters.lang;

import java.util.Arrays;

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.db.models.jooq.ppc.tables.records.CampOptionsRecord;
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.BannerLanguage;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Banner;
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.enums.AdGroupType;
import ru.yandex.autotests.directapi.enums.CampaignLanguage;
import ru.yandex.autotests.directapi.model.api5.adgroups.AdGroupAddItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.AdAddItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.TextAdAddMap;
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.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.CoreMatchers.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 buhter on 15.12.15.
 * https://st.yandex-team.ru/TESTIRT-8041
 */
@Aqua.Test
@Tag(TagDictionary.TRUNK)
@Tag(TagDictionary.RELEASE)
@Title("Транспорт: отправка в БК поля Lang баннера при выставлении языка на кампанию")
@Stories(StoriesNames.BANNER_PARAMS_LANG)
@Features(FeatureNames.BANNERS)
@Issue("https://st.yandex-team.ru/DIRECT-48272")
@RunWith(Parameterized.class)
public class BsTransportOfBannerLangFromCampaignTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;

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

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

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

    private static int shard;
    private Banner banner;

    @Parameterized.Parameter(0)
    public String title;
    @Parameterized.Parameter(1)
    public String titleExtension;
    @Parameterized.Parameter(2)
    public String body;
    @Parameterized.Parameter(3)
    public Long regionId;
    @Parameterized.Parameter(4)
    public CampaignLanguage campaignLanguage;
    @Parameterized.Parameter(5)
    public BannerLanguage lang;

    @Parameterized.Parameters(name = "заголовок 1 = {0}; заголовок 2 = {1}; текст = {2}; язык на кампании = {4}")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {"Заголовок", null, "Текст баннера", RegionIDValues.ENGLAND.getId().longValue()
                        , CampaignLanguage.ENGLISH, BannerLanguage.ENGLISH},  //body&title - ru
                {"Заголовок", "Второй заголовок", "Текст баннера", RegionIDValues.ENGLAND.getId().longValue()
                        , CampaignLanguage.ENGLISH, BannerLanguage.ENGLISH},
                {"Title", null, "Body text", RegionIDValues.KAZAKHSTAN.getId().longValue()
                        , CampaignLanguage.KAZAKH, BannerLanguage.KAZAKH},  //body&title - en
                {"Тақырыбы", null, "Жарнама қазақ тілінде", RegionIDValues.UKRAINE.getId().longValue()
                        , CampaignLanguage.UKRAINIAN, BannerLanguage.UKRAINIAN},  //body&title - kz
                {"Оголошення українською", null, "Реклама українською мовою", RegionIDValues.RUSSIA.getId().longValue()
                        , CampaignLanguage.RUSSIAN, BannerLanguage.RUSSIAN}, //body&title - uk
                {"Başlık türkçe", null, "Burada reklam olabilir", RegionIDValues.EUROPE.getId().longValue()
                        , CampaignLanguage.GERMAN, BannerLanguage.GERMAN}, //body&title - tr
                {"Schnitzel mit Kartoffelpüree", null, "Hitler kaputt. Hände hoch!",
                        RegionIDValues.TURKEY.getId().longValue(), CampaignLanguage.TURKISH, BannerLanguage.TURKISH},
                //body&title - de
                {"Тақырыбы", null, "Жарнама қазақ тілінде", RegionIDValues.BELARUS.getId().longValue()
                        , CampaignLanguage.BELARUSIAN, BannerLanguage.BELARUSIAN},  //body&title - kz
        });
    }

    @BeforeClass
    public static void init() {
        shard = api.userSteps.getDarkSideSteps().getClientFakeSteps().getUserShard(LOGIN);
        api.userSteps.getDirectJooqDbSteps().useShard(shard);
    }

    @Before
    @Step("Подготовка данных для теста")
    public void createBanner() {
        Long cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        CampOptionsRecord campOptions = api.userSteps.getDirectJooqDbSteps().campaignsSteps().getCampOptionsById(cid);
        campOptions.setContentLang(campaignLanguage.value());
        api.userSteps.getDirectJooqDbSteps().campaignsSteps().updateCampOptions(campOptions);

        Long pid = api.userSteps.adGroupsSteps().addGroup(
                new AdGroupAddItemMap().defaultAdGroupAddItem(cid)
                        .withDefaultGroup(AdGroupType.BASE)
                        .withRegionIds(regionId));

        Long bid = api.userSteps.adsSteps().addAd(new AdAddItemMap()
                .withAdGroupId(pid)
                .withTextAd(new TextAdAddMap()
                        .defaultTextAd()
                        .withText(body)
                        .withTitle(title)
                        .withTitle2(titleExtension)
                ));
        Long keywordId = api.userSteps.keywordsSteps().addDefaultKeyword(pid);
        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(keywordId);

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

    @Test
    @Title("Проверяем, что отправляемый Banner.Lang переопределяется полем camp_options.content_lang ")
    public void checkBannerLang() {
        assertThat("в БК отправлен язык баннера", banner.getLang(), equalTo(lang.toString()));
    }
}
