package ru.yandex.autotests.directapi.changes.check;

import com.yandex.direct.api.v5.changes.CheckDictionariesRequest;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
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.utils.config.DirectTestRunProperties;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.ApiResponseHandler;
import ru.yandex.autotests.directapi.apiclient.HttpMessage;
import ru.yandex.autotests.directapi.apiclient.RequestHeader;
import ru.yandex.autotests.directapi.apiclient.config.ConnectionConfig;
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.apiclient.version5.ServiceNames;
import ru.yandex.autotests.directapi.changes.ChangesFeatures;
import ru.yandex.autotests.directapi.changes.ChangesLogins;
import ru.yandex.autotests.directapi.model.api5.changes.CheckDictionariesRequestMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.httpclient.lite.core.config.HttpClientConnectionConfig;
import ru.yandex.autotests.httpclient.lite.core.config.HttpClientFactory;
import ru.yandex.autotests.irt.testutils.allure.LogSteps;
import ru.yandex.autotests.irt.testutils.json.JsonUtils;
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 java.io.IOException;
import java.util.Arrays;
import java.util.Collection;

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

/**
 * Created by ginger on 25.06.15.
 * https://st.yandex-team.ru/TESTIRT-6065
 */
@Aqua.Test
@Features(ChangesFeatures.CHECK)
@Issue("https://st.yandex-team.ru/DIRECT-43042")
@Description("Проверка невалидного JSON.")
@RunWith(Parameterized.class)
public class MalformedJsonTest {
    private static LogSteps log = LogSteps.getLogger(MalformedJsonTest.class);

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

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

    @Rule
    public Trashman trashman = new Trashman(api);
    private static String emptyString = "";

    @Parameterized.Parameter()
    public String operatorLogin;

    @Parameterized.Parameter(1)
    public String subclientLogin;

    @Parameterized.Parameters(name = "loginForAuth = {0}, Client-Login = {1}")
    public static Collection testLogins() {
        Object[][] data = new Object[][]{
                {ChangesLogins.CHANGES_CLIENT, ChangesLogins.CHANGES_CLIENT},
                {ChangesLogins.AGENCY_1_CAMPAIGNS, null}
        };
        return Arrays.asList(data);
    }

    @Test
    @Issue("https://st.yandex-team.ru/DIRECT-43042")
    @ru.yandex.qatools.allure.annotations.TestCaseId("3463")
    public void tryCallCheckWithInvalidField() throws IOException {
        String endpoint = (new ConnectionConfig(DirectTestRunProperties.getInstance().getDirectAPIHost()))
                .getEndPointForV5(
                        (new ConnectionConfig(DirectTestRunProperties.getInstance().getDirectAPIHost())).getProtocolType(), ServiceNames.CHANGES.toString());
        HttpMessage message = new HttpMessage();
        message.setUrl(endpoint);
        message.setRequest(emptyString);
        HttpPost httpRequest = new HttpPost(endpoint);
        httpRequest.addHeader("Authorization","Bearer "+new RequestHeader(operatorLogin).getToken());
        if (subclientLogin != null) {
            httpRequest.addHeader("Client-Login",subclientLogin);
        }
        HttpClientConnectionConfig clientConnectionConfig =
                ConnectionConfig.getHttpClientConnectionConfig(endpoint);
        CloseableHttpClient httpClient = HttpClientFactory.getHttpClient(clientConnectionConfig);
        String response = httpClient.execute(httpRequest, new ApiResponseHandler(message)).getResponseObject();
        response = api.userSteps.jsonClientV5().getResponseResult(response);
        Api5JsonError error = JsonUtils.getObject(response, Api5JsonError.class);
        log.info("Делаем невалидный JSON запрос\n" + message.toString());
        assertThat("получили верную ошибку",
                error,
                Api5JsonErrorMatcher.equalToIgnoreLocale(
                        new Api5Error(8000, Api5ErrorDetails.UNABLE_TO_PROCESS_JSON).toJsonError()));

    }

}
