package ru.yandex.autotests.direct.api.adgroups.add;

import java.util.Arrays;
import java.util.Collection;

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.api.adgroups.AdGroupsFeatures;
import ru.yandex.autotests.direct.api.adgroups.AdGroupsLogins;
import ru.yandex.autotests.direct.api.adgroups.AdGroupsStories;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.UsersRecord;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.model.api5.adgroups.AdGroupAddItemMap;
import ru.yandex.autotests.directapi.model.api5.adgroups.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
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.Stories;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

/**
 * Author hmepas
 * Date 25.07.16
 * https://st.yandex-team.ru/TESTIRT-9856
 */
@Aqua.Test
@Features(AdGroupsFeatures.ADD)
@Stories(AdGroupsStories.AUTHORIZATION)
@RunWith(Parameterized.class)
@Description("Проверка правильности соответствия токена и заголовка Client-Login")
public class ClientAuthorizationHeaderAndTokenLoginMatching {

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

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

    private static Long clientId;

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

    @Parameterized.Parameter(0)
    public String authenticationLogin;

    @Parameterized.Parameter(1)
    public String dbFieldLogin;

    @Parameterized.Parameter(2)
    public String headerLogin;

    @Parameterized.Parameters(name = "dbLogin = {0}, headerLogin = {1}")
    public static Collection testData() {
        Object[][] data = new Object[][]{
                // vasya VASYA Vasya - это один и тот же логи
                {AdGroupsLogins.CLIENT_CAPS_LOGIN, "at-direct-CAPS-LOGIN", "at-direct-CAPS-LOGIN" },
                // ya-vasya и ya.vasya - это один и тот же логин
                {AdGroupsLogins.CLIENT_CAPS_LOGIN, "at-direct.CAPS.LOGIN", "at-direct-CAPS-LOGIN" },
                {AdGroupsLogins.CLIENT_CAPS_LOGIN, "at-direct.CAPS.LOGIN", "at-direct-caps-login" },
                {AdGroupsLogins.CLIENT_CAPS_LOGIN, "at-direct-caps-login", "at-direct.CapS.LOGIN" }
        };
        return Arrays.asList(data);
    }

    @BeforeClass
    public static void initTest() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(AdGroupsLogins.CLIENT_CAPS_LOGIN);
        jooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShardForLogin(AdGroupsLogins.CLIENT_CAPS_LOGIN);
        clientId = Long.valueOf(
                api.userSteps.clientFakeSteps().getClientData(AdGroupsLogins.CLIENT_CAPS_LOGIN).getClientID());
    }

    @Before
    public void clear() {
        // Записываем в БД не нормализованную форму, т.к. такие старые логины в БД попадаются
        final UsersRecord user = jooqDbSteps.usersSteps().getUsersByClientId(clientId);
        user.setLogin(dbFieldLogin);
        jooqDbSteps.usersSteps().updateUsers(user);
    }

    @Test
    public void notNormalizedInDdAndHeaderComparesOk() {
        Long campaignId = api.as(authenticationLogin).userSteps.campaignSteps().addDefaultTextCampaign();

        api.userSteps.adGroupsSteps().shouldGetResultOnAdd(
                new AddRequestMap().withAdGroups(
                        new AdGroupAddItemMap()
                                .withCampaignId(campaignId)
                                .withName(AdGroupAddItemMap.DEFAULT_NAME)
                                .withRegionIds(0L)
                ),
                headerLogin,
                ExpectedResult.success()
        );

    }
}
