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

import java.util.Arrays;

import com.yandex.direct.api.v5.ads.AdFieldEnum;
import com.yandex.direct.api.v5.ads.AdGetItem;
import com.yandex.direct.api.v5.ads.AddResponse;
import com.yandex.direct.api.v5.ads.GetResponse;
import com.yandex.direct.api.v5.ads.TextAdFieldEnum;
import org.junit.AfterClass;
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.db.models.jooq.ppc.enums.BannerImagesFormatsImageType;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetails;
import ru.yandex.autotests.directapi.common.api45.AdImage;
import ru.yandex.autotests.directapi.enums.ImageType;
import ru.yandex.autotests.directapi.model.api5.ads.AdAddItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.AdGetItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.AddRequestMap;
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.TextAdAddMap;
import ru.yandex.autotests.directapi.model.api5.ads.TextAdGetMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.Notification;
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.hazelcast.SemaphoreRule;

import static ru.yandex.autotests.directapi.matchers.beans.version5.BeanDifferMatcherV5.beanEquivalentV5;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;

/**
 * Created by pavryabov on 14.04.15.
 * https://st.yandex-team.ru/TESTIRT-5093
 */
@Aqua.Test
@Features(AdsFeatures.ADD)
@Description("Проверка доступа к AdImageHash в текстовых объявлениях")
@Issue("https://st.yandex-team.ru/DIRECT-34558")
public class AdImageHashTest {

    private static String client = AdsLogins.CLIENT1;

    @ClassRule
    public static ApiSteps api = new ApiSteps().version(104).as(client);

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

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

    Long adGroupId;
    private String adImageHash;
    private String adBigImageHash;
    private static String smallAdImageHash;


    @BeforeClass
    public static void initTest() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
    }

    @Before
    public void configImage() {
        api.as(client);
        Long campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign(client);
        adGroupId = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
    }

    @Test
    public void addWithMyAdImageHash() {
        //DIRECT-41119

        adImageHash = api.userSteps.imagesSteps().configLoginImages(client, ImageType.REGULAR, 1)[0];
        AddResponse response = api.userSteps.adsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withAds(new AdAddItemMap()
                                .withTextAd(new TextAdAddMap().defaultTextAd().withAdImageHash(adImageHash))
                                .withAdGroupId(adGroupId)),
                ExpectedResult.success());
        Long id = response.getAddResults().get(0).getId();
        GetResponse getResponse = api.userSteps.adsSteps().adsGet(new GetRequestMap()
                .withSelectionCriteria(new AdsSelectionCriteriaMap().withIds(id))
                .withFieldNames(AdFieldEnum.ID)
                .withTextAdFieldNames(TextAdFieldEnum.AD_IMAGE_HASH));
        assertThat("AdImageHash сохранился верно", getResponse.getAds(), beanEquivalentV5(
                Arrays.asList((AdGetItem) new AdGetItemMap().withId(id)
                        .withTextAd(new TextAdGetMap().withAdImageHash(adImageHash)).getBean())));
    }

    @Issue("https://st.yandex-team.ru/DIRECT-49536")
    @Test
    public void addWithMyAdBigImageHash() {
        adBigImageHash = api.userSteps.imagesSteps().configLoginImages(client, ImageType.REGULAR, 1)[0];
        AddResponse response = api.userSteps.adsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withAds(new AdAddItemMap()
                                .withTextAd(new TextAdAddMap().defaultTextAd().withAdImageHash(adBigImageHash))
                                .withAdGroupId(adGroupId)),
                ExpectedResult.success());
        Long id = response.getAddResults().get(0).getId();
        GetResponse getResponse = api.userSteps.adsSteps().adsGet(new GetRequestMap()
                .withSelectionCriteria(new AdsSelectionCriteriaMap().withIds(id))
                .withFieldNames(AdFieldEnum.ID)
                .withTextAdFieldNames(TextAdFieldEnum.AD_IMAGE_HASH));
        assertThat("AdImageHash сохранился верно", getResponse.getAds(), beanEquivalentV5(
                Arrays.asList((AdGetItem) new AdGetItemMap().withId(id)
                        .withTextAd(new TextAdGetMap().withAdImageHash(adBigImageHash)).getBean())));
    }

    @Test
    public void addWithNotMyAdImageHash() {

        adImageHash = api.userSteps.imagesSteps().configLoginImages(client, ImageType.REGULAR, 1)[0];
        api.as(AdsLogins.CLIENT_ELSE);
        Long campaignIdElse = api.userSteps.campaignSteps().addDefaultTextCampaign(AdsLogins.CLIENT_ELSE);
        Long adGroupIdElse = api.userSteps.adGroupsSteps().addDefaultGroup(campaignIdElse);
        api.userSteps.adsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withAds(new AdAddItemMap()
                                .withTextAd(new TextAdAddMap().defaultTextAd().withAdImageHash(adImageHash))
                                .withAdGroupId(adGroupIdElse)),
                ExpectedResult.errors(new Notification(8800, Api5ErrorDetails.IMAGE_NOT_FOUND)));
    }

    @Test
    public void addWithNonExistentAdImageHash() {
        api.userSteps.adsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withAds(new AdAddItemMap()
                                .withTextAd(new TextAdAddMap().defaultTextAd().withAdImageHash("11111111"))
                                .withAdGroupId(adGroupId)),
                ExpectedResult.errors(new Notification(8800, Api5ErrorDetails.IMAGE_NOT_FOUND)));
    }

    @Test
    public void addWithDeletedAdImageHash() {

        adImageHash = api.userSteps.imagesSteps().configLoginImages(client, ImageType.REGULAR, 1)[0];
        api.userSteps.imagesSteps().adImageDelete(adImageHash);
        api.userSteps.adsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withAds(new AdAddItemMap()
                                .withTextAd(new TextAdAddMap().defaultTextAd().withAdImageHash(adImageHash))
                                .withAdGroupId(adGroupId)),
                ExpectedResult.errors(new Notification(8800, Api5ErrorDetails.IMAGE_NOT_FOUND)));
    }

    @Test
    public void addWithEmptyAdImageHash() {
        api.userSteps.adsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withAds(new AdAddItemMap()
                                .withTextAd(new TextAdAddMap().defaultTextAd().withAdImageHash(""))
                                .withAdGroupId(adGroupId)),
                ExpectedResult.errors(new Notification(8800, Api5ErrorDetails.IMAGE_NOT_FOUND)));
    }

    @Test
    public void addWithSpaceAdImageHash() {
        api.userSteps.adsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withAds(new AdAddItemMap()
                                .withTextAd(new TextAdAddMap().defaultTextAd().withAdImageHash(" "))
                                .withAdGroupId(adGroupId)),
                ExpectedResult.errors(new Notification(8800, Api5ErrorDetails.IMAGE_NOT_FOUND)));
    }


    @Test
    @Issue("DIRECT-49672")
    public void addWithOldSmallAdImageHash() {
        AdImage adImage = api.userSteps.imagesSteps()
                .uploadRawImage("earth", "https://direct-qa.s3.mds.yandex.net/images/earth600x450.jpg", client);
        smallAdImageHash = adImage.getAdImageHash();
        api.userSteps.getDirectJooqDbSteps().useShardForLogin(client)
                .imagesSteps().setImageType(smallAdImageHash, BannerImagesFormatsImageType.small);

        api.userSteps.adsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withAds(new AdAddItemMap()
                                .withTextAd(new TextAdAddMap().defaultTextAd().withAdImageHash(smallAdImageHash))
                                .withAdGroupId(adGroupId)),
                ExpectedResult.errors(new Notification(6000, Api5ErrorDetails.INVALID_AD_IMAGE_TYPE_FOR_THIS_BANNER)));
    }

    @Test
    public void addWithImageAdAdImageHash() {
        String imageAdAdImageHash = api.userSteps.imagesStepsV5().addDefaultImageAdAdImage();
        api.userSteps.adsSteps().shouldGetResultOnAdd(new AddRequestMap()
                        .withAds(new AdAddItemMap()
                                .withTextAd(new TextAdAddMap().defaultTextAd().withAdImageHash(imageAdAdImageHash))
                                .withAdGroupId(adGroupId)),
                ExpectedResult.errors(new Notification(6000, Api5ErrorDetails.INVALID_AD_IMAGE_TYPE_FOR_THIS_BANNER)));
    }

    @AfterClass
    public static void removeSmallImage() {
        api.userSteps.getDirectJooqDbSteps().useShardForLogin(client)
                .imagesSteps().deleteBannerImagesFormatsRecord(smallAdImageHash);
    }
}
