package ru.yandex.autotests.directapi.keywords.update;

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

import org.junit.Before;
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.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.Api5Error;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetails;
import ru.yandex.autotests.directapi.apiclient.errors.Api5JsonError;
import ru.yandex.autotests.directapi.apiclient.errors.Api5JsonErrorMatcher;
import ru.yandex.autotests.directapi.keywords.KeywordsFeatures;
import ru.yandex.autotests.directapi.keywords.KeywordsLogins;
import ru.yandex.autotests.directapi.model.Logins;
import ru.yandex.autotests.directapi.model.api5.Action;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.Notification;
import ru.yandex.autotests.directapi.model.api5.keywords.KeywordUpdateMap;
import ru.yandex.autotests.directapi.model.api5.keywords.UpdateRequestMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.irt.testutils.allure.LogSteps;
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.Step;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;

/**
 * Created by gerdler on 17.04.17.
 * https://st.yandex-team.ru/DIRECT-64666
 */
@Aqua.Test
@Features(KeywordsFeatures.UPDATE)
@Issue("https://st.yandex-team.ru/DIRECT-64386")
@Description("Обновление автотаргетинга от имени внутренних ролей")
@RunWith(Parameterized.class)
public class UpdateAutotargetingRolesAccessTest {

    private static LogSteps log = LogSteps.getLogger(UpdateAutotargetingRolesAccessTest.class);

    @ClassRule
    public static ApiSteps api = new ApiSteps();

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

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

    @Parameterized.Parameter(0)
    public String autotargetingCreater;

    @Parameterized.Parameter(1)
    public String autotargetingUpdater;

    @Parameterized.Parameter(2)
    public String client;

    @Parameterized.Parameter(3)
    public ExpectedResult expectedResult;

    @Parameterized.Parameter(4)
    public Api5Error expectedError;

    @Parameterized.Parameters(name = "create = {0}, update = {1}, client = {2}")
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {Logins.MANAGER_DEFAULT, Logins.MANAGER_DEFAULT, KeywordsLogins.SERV_CLIENT,
                        ExpectedResult.success(), null},
                {Logins.SUPER_LOGIN, Logins.PLACER, KeywordsLogins.SINGLE_CLIENT_UPDATE,
                        ExpectedResult.errors(new Notification(54, Api5ErrorDetails.NO_RIGHTS_TO_WRITE)),
                        new Api5Error(54)},
                {Logins.SUPER_LOGIN, Logins.SUPPORT, KeywordsLogins.SINGLE_CLIENT_UPDATE,
                        ExpectedResult.success(), null},
                {Logins.SUPER_LOGIN, Logins.SUPER_LOGIN, KeywordsLogins.SINGLE_CLIENT_UPDATE,
                        ExpectedResult.success(), null},
                {Logins.SUPER_LOGIN, KeywordsLogins.SINGLE_CLIENT_UPDATE, KeywordsLogins.SINGLE_CLIENT_UPDATE,
                        ExpectedResult.success(), null},
                {Logins.SUPER_LOGIN, KeywordsLogins.SINGLE_CLIENT_REP, KeywordsLogins.SINGLE_CLIENT,
                        ExpectedResult.success(), null},
                {KeywordsLogins.AGENCY, KeywordsLogins.AGENCY, KeywordsLogins.SUBCLIENT,
                        ExpectedResult.success(), null},
                {KeywordsLogins.AGENCY_REP, KeywordsLogins.AGENCY_REP, KeywordsLogins.SUBCLIENT,
                        ExpectedResult.success(), null},

                {Logins.SUPER_LOGIN, Logins.MEDIA, KeywordsLogins.SINGLE_CLIENT_UPDATE,
                        ExpectedResult.errors(new Notification(54, Api5ErrorDetails.NO_RIGHTS_TO_WRITE)),
                        new Api5Error(54)
                },
                {Logins.SUPER_LOGIN, Logins.SUPER_READER, KeywordsLogins.SINGLE_CLIENT_UPDATE,
                        ExpectedResult.errors(new Notification(54, Api5ErrorDetails.NO_RIGHTS_TO_WRITE)),
                        new Api5Error(54)
                },
                {KeywordsLogins.AGENCY, KeywordsLogins.SUBCLIENT, KeywordsLogins.SUBCLIENT,
                        ExpectedResult.errors(new Notification(54, Api5ErrorDetails.NO_RIGHTS_TO_WRITE)),
                        new Api5Error(54)
                }
        });
    }

    private Long autotargetingId;

    @Before
    @Step("Подготовка данных для теста")
    public void prepareKeyword() {
        log.info("Сбросим использованные баллы");
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(autotargetingUpdater);
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(autotargetingCreater);

        log.info("Создадим автотаргетинг от имени " + autotargetingCreater);
        api.as(autotargetingCreater);
        Long campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign(client);
        long adGroupId = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId, client);
        autotargetingId = api.userSteps.keywordsSteps().addAutotargeting(client, adGroupId);
    }

    @Test
    public void updateAutotargetingRolesTest() {
        try {
            api.as(autotargetingUpdater).userSteps.keywordsSteps().shouldGetResultOn(
                    Action.UPDATE,
                    client,
                    new UpdateRequestMap().withKeywords(new KeywordUpdateMap().withId(autotargetingId)),
                    expectedResult
            );
        } catch (Api5JsonError jsonError) {
            // Java версия сервиса возвращает 54-ю ошибку на весь запрос см. DIRECT-77051
            if (expectedError == null) {
                throw new AssertionError("неожиданная ошибка", jsonError);
            } else {
                assertThat("совпал текст ошибки (JSON)",
                        jsonError, Api5JsonErrorMatcher.equalToIgnoreLocale(expectedError.toJsonError()));
            }
        }
    }
}
