package ru.yandex.autotests.directapi.images.adimage.get;

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.enums.UsersHidden;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.enums.ImageType;
import ru.yandex.autotests.directapi.images.ImagesFeatures;
import ru.yandex.autotests.irt.testutils.allure.LogSteps;
import ru.yandex.autotests.directapi.apiclient.errors.AxisError;
import ru.yandex.autotests.directapi.apiclient.errors.AxisErrorDetails;
import ru.yandex.autotests.directapi.apiclient.methods.Action;
import ru.yandex.autotests.directapi.apiclient.methods.Method;
import ru.yandex.autotests.directapi.common.api45.AdImageResponse;
import ru.yandex.autotests.directapi.common.api45.ShortClientInfo;
import ru.yandex.autotests.directapi.model.Logins;
import ru.yandex.autotests.directapi.model.images.AdImageMap;
import ru.yandex.autotests.directapi.model.images.AdImageRequestMap;
import ru.yandex.autotests.directapi.model.images.AdImageSelectionCriteriaMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.hazelcast.SemaphoreRule;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.directapi.steps.banners.ImagesSteps;
import ru.yandex.qatools.allure.annotations.Features;

import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import static ch.lambdaj.Lambda.extractProperty;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.core.IsCollectionContaining.hasItems;
import static org.junit.Assert.assertThat;

/**
 * User: mariabye
 * Date: 22.05.13
 */
@Aqua.Test
@Features(ImagesFeatures.AD_IMAGE_GET)
@RunWith(Parameterized.class)
@Tag(TagDictionary.TRUNK)
public class GetImagesInternalRolesTest {
    private LogSteps log = LogSteps.getLogger(this.getClass());

    @ClassRule
    public static ApiSteps api = new ApiSteps().version(104);
    private static DirectJooqDbSteps jooqDbSteps;

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

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

    @Parameterized.Parameter
    public String operator;
    @Parameterized.Parameter(value = 1)
    public String login;
    @Parameterized.Parameter(value = 2)
    public String loginAnother;

    private static String managerClientLogin;
    private static String managerClientLoginAnother;
    private static String agencyClientLogin;
    private static String agencyClientLoginAnother;

    @Parameterized.Parameters(name = "operator = {0}")
    public static Collection roleValues() {
        List<ShortClientInfo> clients = api.as(Logins.MANAGER_DEFAULT).userSteps.clientSteps()
                .getSubClientsNotArch(Logins.MANAGER_DEFAULT);
        managerClientLogin = clients.get(1).getLogin();
        managerClientLoginAnother = clients.get(2).getLogin();

        // NB: пометим пользователя как тестового, чтоб бы для него не блокировался доступ к АПИ
        // https://st.yandex-team.ru/DIRECT-53676
        jooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShardForLogin(managerClientLogin);
        Long managerClientUid = jooqDbSteps.usersSteps().getUidByLogin(managerClientLogin);
        jooqDbSteps.usersSteps().setUsersHidden(managerClientUid, UsersHidden.Yes);

        api.userSteps.imagesSteps().configLoginImages(managerClientLogin, ImageType.REGULAR, 1, 2);

        clients = api.as(Logins.AGENCY_YE_DEFAULT).userSteps.clientSteps()
                .getSubClientsNotArch(Logins.AGENCY_YE_DEFAULT);
        agencyClientLogin = clients.get(1).getLogin();
        agencyClientLoginAnother = clients.get(2).getLogin();



        clientImages = api.userSteps.imagesSteps().configLoginImages(agencyClientLogin, ImageType.REGULAR, 1, 2);


        Object[][] data = new Object[][]{
                {Logins.SUPER_LOGIN, managerClientLogin, agencyClientLoginAnother},
                {Logins.SUPPORT, agencyClientLogin, managerClientLoginAnother},
                {Logins.PLACER, agencyClientLogin, managerClientLoginAnother},
                {Logins.SUPER_READER, managerClientLogin, agencyClientLoginAnother},
                {Logins.MEDIA, managerClientLogin, managerClientLoginAnother},
                {Logins.MANAGER_DEFAULT, managerClientLogin, managerClientLoginAnother},
                {Logins.AGENCY_YE_DEFAULT, agencyClientLogin, agencyClientLoginAnother}
        };
        return Arrays.asList(data);
    }

    private static String[] clientImages;

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("7461")
    public void getImagesByUndefLogin() {
        api.as(operator).userSteps.imagesSteps().shouldGetErrorOn(
                Method.AD_IMAGE,
                new AdImageRequestMap<>(api.type())
                        .getImage(new AdImageSelectionCriteriaMap(api.type())),
                new AxisError(71, AxisErrorDetails.FIELD_MUST_NOT_BE_EMPTY, "SelectionCriteria.Logins")
        );
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("7462")
    public void getImagesByEmptyLoginArray() {
        api.as(operator).userSteps.imagesSteps().shouldGetErrorOn(
                Method.AD_IMAGE,
                new AdImageRequestMap<>(api.type())
                        .getImage(new AdImageSelectionCriteriaMap(api.type())
                                .withLogins(new String[0])),
                new AxisError(30, AxisErrorDetails.THE_ARRAY_CANNOT_BE_EMPTY, "SelectionCriteria.Logins")
        );
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("7463")
    public void getImagesByClientLoginArray() {
        AdImageResponse imageResponse = api.as(operator).userSteps.imagesSteps().adImageGet(
                new AdImageSelectionCriteriaMap(api.type())
                        .withLogins(login));

        List<String> gotHashes = extractProperty(imageResponse.getAdImages(), AdImageMap.AD_IMAGE_HASH);

        assertThat("Не вернулись картинки пользвателя", gotHashes, contains(clientImages));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("7464")
    public void getImagesByAgencyLogin() {
            api.as(operator).userSteps.imagesSteps().shouldGetErrorOn(
                    Method.AD_IMAGE,
                    new AdImageRequestMap<>(api.type())
                            .withAction(Action.GET)
                            .withAdImageSelectionCriteria(new AdImageSelectionCriteriaMap(api.type())
                                    .withLogins(Logins.AGENCY_YE_DEFAULT)),
                    new AxisError(251, AxisErrorDetails.NO_ONE_VALID_LOGIN));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("7465")
    public void getImagesByInternalLogin() {
        api.as(operator).userSteps.imagesSteps().shouldGetErrorOn(
                Method.AD_IMAGE,
                new AdImageRequestMap<>(api.type())
                        .withAction(Action.GET)
                        .withAdImageSelectionCriteria(new AdImageSelectionCriteriaMap(api.type())
                                .withLogins(operator)),
                new AxisError(251, AxisErrorDetails.NO_ONE_VALID_LOGIN));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("7466")
    public void getImagesByClientsLoginArray() {
        AdImageResponse imageResponse = api.as(operator).userSteps.imagesSteps().adImageGet(
                new AdImageSelectionCriteriaMap(api.type())
                        .withLogins(login, loginAnother));

        List<String> gotHashes = extractProperty(imageResponse.getAdImages(), AdImageMap.AD_IMAGE_HASH);

        assertThat("Не вернулись картинки для нескольких логинов", gotHashes, hasItems(clientImages));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("7467")
    public void getImagesByLimitClientsLoginArray() {
        String[] logins = new String[ImagesSteps.AD_IMAGE_GET_LOGIN_MAX_COUNT];
        Arrays.fill(logins, login);
        AdImageResponse imageResponse = api.as(operator).userSteps.imagesSteps().adImageGet(
                new AdImageSelectionCriteriaMap(api.type())
                        .withLogins(login));

        List<String> gotHashes = extractProperty(imageResponse.getAdImages(), AdImageMap.AD_IMAGE_HASH);

        assertThat("Не вернулись картинки для максимального значения логинов в списке",
                gotHashes, contains(clientImages));
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("7468")
    public void getImagesByOverLimitClientsLoginArray() {
        String[] logins = new String[ImagesSteps.AD_IMAGE_GET_LOGIN_MAX_COUNT + 1];
        Arrays.fill(logins, login);
        api.as(operator).userSteps.imagesSteps().shouldGetErrorOn(
                Method.AD_IMAGE,
                new AdImageRequestMap<>(api.type())
                        .withAction(Action.GET)
                        .withAdImageSelectionCriteria(new AdImageSelectionCriteriaMap(api.type())
                                .withLogins(logins)),
                new AxisError(241, AxisErrorDetails.THE_ARRAY_MUST_CONTAIN_NO_MORE_THAN_N_ELEMENTS,
                        "SelectionCriteria.Logins", ImagesSteps.AD_IMAGE_GET_LOGIN_MAX_COUNT));
    }
}
