package ru.yandex.autotests.direct.api.ads.update.textad;

import java.util.List;

import com.yandex.direct.api.v5.ads.AdFieldEnum;
import com.yandex.direct.api.v5.ads.AdGetItem;
import com.yandex.direct.api.v5.ads.GetResponse;
import com.yandex.direct.api.v5.ads.TextAdFieldEnum;
import com.yandex.direct.api.v5.ads.TextAdGet;
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.api.ads.AdsFeatures;
import ru.yandex.autotests.direct.api.ads.AdsLogins;
import ru.yandex.autotests.direct.api.ads.AdsStories;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.enums.BannerType;
import ru.yandex.autotests.directapi.model.api5.ads.AdGetItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.AdUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.AdsSelectionCriteriaMap;
import ru.yandex.autotests.directapi.model.api5.ads.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.ads.TextAdGetMap;
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.general.ExpectedResult;
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.directapi.rules.Trashman;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Issue;
import ru.yandex.qatools.allure.annotations.Stories;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static ru.yandex.autotests.directapi.matchers.beandiffer2.BeanDifferMatcherV5.beanDifferV5;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

@Aqua.Test
@Features(AdsFeatures.UPDATE)
@Stories(AdsStories.TEXT_AD)
@Issue("https://st.yandex-team.ru/DIRECT-65083")
@Description("Обновление основной ссылки объявления при одновременном удалении набора быстрых ссылок")
public class UpdateHrefAndClearSitelinkSetTest {

    private static final String LOGIN = AdsLogins.CLIENT;

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

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

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

    private static final String HREF = "http://thehref.ru/";


    private static long adGroupId;
    private static long sitelinkSetId;

    private long adID;

    @BeforeClass
    public static void init() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(LOGIN);

        long campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign(LOGIN);
        adGroupId = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);

        List<Long> sitelinkSetAddedIds = api.userSteps.sitelinksSteps().add(new AddRequestMap()
                .withSitelinksSets(new SitelinksSetAddItemMap()
                        .withSitelinks(new SitelinkMap()
                                .withHref(HREF)
                                .withRandomDescription()
                                .withRandomTitle())));

        assumeThat("Создан набор быстрых ссылок", sitelinkSetAddedIds, hasSize(1));

        sitelinkSetId = sitelinkSetAddedIds.get(0);
    }

    @Before
    public void createAdWithSitelinkSet() {
        adID = api.userSteps.adsSteps().addAdWithSitelinkSetId(adGroupId, BannerType.TEXT, sitelinkSetId);
        GetResponse response = api.userSteps.adsSteps().adsGet(new GetRequestMap()
                .withFieldNames(AdFieldEnum.ID)
                .withTextAdFieldNames(TextAdFieldEnum.HREF, TextAdFieldEnum.SITELINK_SET_ID)
                .withSelectionCriteria(new AdsSelectionCriteriaMap()
                        .withIds(adID)));

        TextAdGet ad = response.getAds().get(0).getTextAd();

        assumeThat("В объявлении содержится созданный набор быстрых ссылок",
                ad.getSitelinkSetId().getValue(), equalTo(sitelinkSetId));
    }

    @Test
    public void updateHrefAndSitelinkSetIdShouldNotCauseError() {
        api.userSteps.adsSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withAds(new AdUpdateItemMap()
                                .withId(adID)
                                .withTextAd(new TextAdUpdateMap()
                                        .withHref(HREF)
                                        .withSitelinkSetId(null))),
                ExpectedResult.success(adID));

        GetResponse response = api.userSteps.adsSteps().adsGet(new GetRequestMap()
                .withFieldNames(AdFieldEnum.ID)
                .withTextAdFieldNames(TextAdFieldEnum.HREF, TextAdFieldEnum.SITELINK_SET_ID)
                .withSelectionCriteria(new AdsSelectionCriteriaMap()
                        .withIds(adID)));

        assertThat("Ссылка сохранилась верно",
                response.getAds().get(0),
                beanDifferV5(
                        (AdGetItem) new AdGetItemMap()
                                .withId(adID)
                                .withTextAd(new TextAdGetMap()
                                        .withHref(HREF)
                                        .withSitelinkSetId(null)).getBean()));
    }

    @Test
    public void updateHrefWithoutSitelinkSetIdShouldNotRemoveSitelinkSetIdFromAd() {
        final String anotherHref = "http://theotherhref.ru/";

        api.userSteps.adsSteps().shouldGetResultOnUpdate(new UpdateRequestMap()
                        .withAds(new AdUpdateItemMap()
                                .withId(adID)
                                .withTextAd(new TextAdUpdateMap()
                                        .withHref(anotherHref))),
                ExpectedResult.success(adID));

        GetResponse response = api.userSteps.adsSteps().adsGet(new GetRequestMap()
                .withFieldNames(AdFieldEnum.ID)
                .withTextAdFieldNames(TextAdFieldEnum.HREF, TextAdFieldEnum.SITELINK_SET_ID)
                .withSelectionCriteria(new AdsSelectionCriteriaMap()
                        .withIds(adID)));

        assertThat("Вернулся прежний ID набора быстрых ссылок",
                response.getAds().get(0).getTextAd().getSitelinkSetId().getValue(),
                equalTo(sitelinkSetId));
    }

}
