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

import java.util.List;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
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.RunBsTransportScriptResponse;
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.darkside.model.bslogs.clientdata.Sitelink;
import ru.yandex.autotests.directapi.model.api5.ads.AdAddItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.AdUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.TextAdAddMap;
import ru.yandex.autotests.directapi.model.api5.ads.TextAdUpdateMap;
import ru.yandex.autotests.directapi.model.api5.ads.UpdateRequestMap;
import ru.yandex.autotests.directapi.model.api5.sitelinks.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.sitelinks.SitelinkMap;
import ru.yandex.autotests.directapi.model.api5.sitelinks.SitelinksSetAddItemMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
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.Description;
import ru.yandex.qatools.allure.annotations.Features;
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.hasSize;
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("Транспорт: проверка отправки описания одного сайтлинка при создании или обновлении объявления")
@Stories(StoriesNames.BANNER_ACTION_CREATION)
@Features(FeatureNames.BANNERS)
public class BsTransportOfOneSitelinkDescriptionTest {

    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 int shard;

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

    private Long cid;
    private Long pid;
    private Long bid;

    private String expectedDescription;

    @Before
    @Step("Подготовка данных для теста")
    public void prepareData() {
        cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        Long bidsId = api.userSteps.keywordsSteps().addDefaultKeyword(pid);

        SitelinkMap sitelinkMap = new SitelinkMap().randomSitelinkWithDescription();
        expectedDescription = ((com.yandex.direct.api.v5.sitelinks.SitelinkAddItem) sitelinkMap.getBean())
                .getDescription();
        List<Long> sitelinksSetIds = api.userSteps.sitelinksSteps().add(new AddRequestMap()
                .withSitelinksSets(new SitelinksSetAddItemMap().withSitelinks(sitelinkMap)));
        assumeThat("был добавлен один набор сайтлинков", sitelinksSetIds, hasSize(1));
        Long sitelinksSetId = sitelinksSetIds.get(0);

        bid = api.userSteps.adsSteps().addAd(new AdAddItemMap()
                .withAdGroupId(pid)
                .withTextAd(new TextAdAddMap()
                        .defaultTextAd()
                        .withSitelinkSetId(sitelinksSetId)));

        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(bidsId);
    }

    @Test
    @Description("Отправка сайтлинков при создании объявления")
    public void sendNewBannerWithSitelinksWithDescription() {
        RunBsTransportScriptResponse response = api.userSteps.getDarkSideSteps().getTransportSteps()
                .sendNewCampaign(shard, cid);
        String description = getSitelinkDescription(response);

        assertThat("описание сайтлинка было отправлено верно", description, equalTo(expectedDescription));
    }

    @Test
    @Description("Отправка сайтлинков при обновлении объявления")
    public void sendUpdatedSitelinksWithDescription() {
        api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);

        SitelinkMap sitelinkMap = new SitelinkMap().randomSitelinkWithDescription();
        expectedDescription = ((com.yandex.direct.api.v5.sitelinks.SitelinkAddItem) sitelinkMap.getBean())
                .getDescription();
        List<Long> sitelinksSetIds = api.userSteps.sitelinksSteps().add(new AddRequestMap()
                .withSitelinksSets(new SitelinksSetAddItemMap()
                        .withSitelinks(sitelinkMap)));
        assumeThat("был добавлен один набор сайтлинков", sitelinksSetIds, hasSize(1));
        Long sitelinksSetId = sitelinksSetIds.get(0);

        api.userSteps.adsSteps().adsUpdate(new UpdateRequestMap().withAds(new AdUpdateItemMap()
                .withId(bid)
                .withTextAd(new TextAdUpdateMap().withSitelinkSetId(sitelinksSetId))));
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);

        RunBsTransportScriptResponse response = api.userSteps.getDarkSideSteps().getTransportSteps()
                .sendCampaign(shard, cid);
        String description = getSitelinkDescription(response);

        assertThat("описание сайтлинка было отправлено верно", description, equalTo(expectedDescription));
    }

    private String getSitelinkDescription(RunBsTransportScriptResponse response) {
        Campaign campaign = api.userSteps.getDarkSideSteps().getTransportSteps()
                .getClientDataRequestCampaign(response, 0, cid);
        Context context = campaign != null ? campaign.getContext(pid) : null;
        Banner banner = context != null ? context.getBanner(bid) : null;
        List<Sitelink> sitelinks = banner != null ? banner.getSitelinks() : null;
        Sitelink sitelink = sitelinks != null && sitelinks.size() > 0 ? sitelinks.get(0) : null;
        return sitelink != null ? sitelink.getDescription() : null;
    }
}
