/**
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 */

package com.microsoft.azure.loganalytics.implementation;

import com.google.common.reflect.TypeToken;
import com.microsoft.azure.AzureClient;
import com.microsoft.azure.AzureServiceClient;
import com.microsoft.azure.loganalytics.LogAnalyticsDataClient;
import com.microsoft.azure.loganalytics.models.ErrorResponseException;
import com.microsoft.azure.loganalytics.models.QueryBody;
import com.microsoft.azure.loganalytics.models.QueryResults;
import com.microsoft.rest.credentials.ServiceClientCredentials;
import com.microsoft.rest.RestClient;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import com.microsoft.rest.Validator;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.Path;
import retrofit2.http.POST;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;

/**
 * Initializes a new instance of the LogAnalyticsDataClientImpl class.
 */
public class LogAnalyticsDataClientImpl extends AzureServiceClient implements LogAnalyticsDataClient {
    /** The Retrofit service to perform REST calls. */
    private LogAnalyticsDataClientService service;
    /** the {@link AzureClient} used for long running operations. */
    private AzureClient azureClient;

    /**
     * Gets the {@link AzureClient} used for long running operations.
     * @return the azure client;
     */
    public AzureClient getAzureClient() {
        return this.azureClient;
    }

    /** The preferred language for the response. */
    private String acceptLanguage;

    /**
     * Gets The preferred language for the response.
     *
     * @return the acceptLanguage value.
     */
    public String acceptLanguage() {
        return this.acceptLanguage;
    }

    /**
     * Sets The preferred language for the response.
     *
     * @param acceptLanguage the acceptLanguage value.
     * @return the service client itself
     */
    public LogAnalyticsDataClientImpl withAcceptLanguage(String acceptLanguage) {
        this.acceptLanguage = acceptLanguage;
        return this;
    }

    /** The retry timeout in seconds for Long Running Operations. Default value is 30. */
    private int longRunningOperationRetryTimeout;

    /**
     * Gets The retry timeout in seconds for Long Running Operations. Default value is 30.
     *
     * @return the longRunningOperationRetryTimeout value.
     */
    public int longRunningOperationRetryTimeout() {
        return this.longRunningOperationRetryTimeout;
    }

    /**
     * Sets The retry timeout in seconds for Long Running Operations. Default value is 30.
     *
     * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value.
     * @return the service client itself
     */
    public LogAnalyticsDataClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) {
        this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout;
        return this;
    }

    /** Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */
    private boolean generateClientRequestId;

    /**
     * Gets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true.
     *
     * @return the generateClientRequestId value.
     */
    public boolean generateClientRequestId() {
        return this.generateClientRequestId;
    }

    /**
     * Sets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true.
     *
     * @param generateClientRequestId the generateClientRequestId value.
     * @return the service client itself
     */
    public LogAnalyticsDataClientImpl withGenerateClientRequestId(boolean generateClientRequestId) {
        this.generateClientRequestId = generateClientRequestId;
        return this;
    }

    /**
     * Initializes an instance of LogAnalyticsDataClient client.
     *
     * @param credentials the management credentials for Azure
     */
    public LogAnalyticsDataClientImpl(ServiceClientCredentials credentials) {
        this("https://api.loganalytics.io/v1", credentials);
    }

    /**
     * Initializes an instance of LogAnalyticsDataClient client.
     *
     * @param baseUrl the base URL of the host
     * @param credentials the management credentials for Azure
     */
    public LogAnalyticsDataClientImpl(String baseUrl, ServiceClientCredentials credentials) {
        super(baseUrl, credentials);
        initialize();
    }

    /**
     * Initializes an instance of LogAnalyticsDataClient client.
     *
     * @param restClient the REST client to connect to Azure.
     */
    public LogAnalyticsDataClientImpl(RestClient restClient) {
        super(restClient);
        initialize();
    }

    protected void initialize() {
        this.acceptLanguage = "en-US";
        this.longRunningOperationRetryTimeout = 30;
        this.generateClientRequestId = true;
        this.azureClient = new AzureClient(this);
        initializeService();
    }

    /**
     * Gets the User-Agent header for the client.
     *
     * @return the user agent string.
     */
    @Override
    public String userAgent() {
        return String.format("%s (%s, %s)", super.userAgent(), "LogAnalyticsDataClient", "v1");
    }

    private void initializeService() {
        service = restClient().retrofit().create(LogAnalyticsDataClientService.class);
    }

    /**
     * The interface defining all the services for LogAnalyticsDataClient to be
     * used by Retrofit to perform actually REST calls.
     */
    interface LogAnalyticsDataClientService {
        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.loganalytics.LogAnalyticsDataClient query" })
        @POST("workspaces/{workspaceId}/query")
        Observable<Response<ResponseBody>> query(@Path("workspaceId") String workspaceId, @Body QueryBody body, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

    }

    /**
     * Execute an Analytics query.
     * Executes an Analytics query for data. [Here](https://dev.loganalytics.io/documentation/Using-the-API) is an example for using POST with an Analytics query.
     *
     * @param workspaceId ID of the workspace. This is Workspace ID from the Properties blade in the Azure portal.
     * @param body The Analytics query. Learn more about the [Analytics query syntax](https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/)
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws ErrorResponseException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the QueryResults object if successful.
     */
    public QueryResults query(String workspaceId, QueryBody body) {
        return queryWithServiceResponseAsync(workspaceId, body).toBlocking().single().body();
    }

    /**
     * Execute an Analytics query.
     * Executes an Analytics query for data. [Here](https://dev.loganalytics.io/documentation/Using-the-API) is an example for using POST with an Analytics query.
     *
     * @param workspaceId ID of the workspace. This is Workspace ID from the Properties blade in the Azure portal.
     * @param body The Analytics query. Learn more about the [Analytics query syntax](https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/)
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<QueryResults> queryAsync(String workspaceId, QueryBody body, final ServiceCallback<QueryResults> serviceCallback) {
        return ServiceFuture.fromResponse(queryWithServiceResponseAsync(workspaceId, body), serviceCallback);
    }

    /**
     * Execute an Analytics query.
     * Executes an Analytics query for data. [Here](https://dev.loganalytics.io/documentation/Using-the-API) is an example for using POST with an Analytics query.
     *
     * @param workspaceId ID of the workspace. This is Workspace ID from the Properties blade in the Azure portal.
     * @param body The Analytics query. Learn more about the [Analytics query syntax](https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/)
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the QueryResults object
     */
    public Observable<QueryResults> queryAsync(String workspaceId, QueryBody body) {
        return queryWithServiceResponseAsync(workspaceId, body).map(new Func1<ServiceResponse<QueryResults>, QueryResults>() {
            @Override
            public QueryResults call(ServiceResponse<QueryResults> response) {
                return response.body();
            }
        });
    }

    /**
     * Execute an Analytics query.
     * Executes an Analytics query for data. [Here](https://dev.loganalytics.io/documentation/Using-the-API) is an example for using POST with an Analytics query.
     *
     * @param workspaceId ID of the workspace. This is Workspace ID from the Properties blade in the Azure portal.
     * @param body The Analytics query. Learn more about the [Analytics query syntax](https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/)
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the QueryResults object
     */
    public Observable<ServiceResponse<QueryResults>> queryWithServiceResponseAsync(String workspaceId, QueryBody body) {
        if (workspaceId == null) {
            throw new IllegalArgumentException("Parameter workspaceId is required and cannot be null.");
        }
        if (body == null) {
            throw new IllegalArgumentException("Parameter body is required and cannot be null.");
        }
        Validator.validate(body);
        return service.query(workspaceId, body, this.acceptLanguage(), this.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<QueryResults>>>() {
                @Override
                public Observable<ServiceResponse<QueryResults>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<QueryResults> clientResponse = queryDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<QueryResults> queryDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException {
        return this.restClient().responseBuilderFactory().<QueryResults, ErrorResponseException>newInstance(this.serializerAdapter())
                .register(200, new TypeToken<QueryResults>() { }.getType())
                .registerError(ErrorResponseException.class)
                .build(response);
    }

}
