/**
 * 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.applicationinsights.query.implementation;

import retrofit2.Retrofit;
import com.microsoft.azure.applicationinsights.query.Querys;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.applicationinsights.query.models.ErrorResponseException;
import com.microsoft.azure.applicationinsights.query.models.QueryBody;
import com.microsoft.azure.applicationinsights.query.models.QueryResults;
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;

/**
 * An instance of this class provides access to all the operations defined
 * in Querys.
 */
public class QuerysImpl implements Querys {
    /** The Retrofit service to perform REST calls. */
    private QuerysService service;
    /** The service client containing this operation class. */
    private ApplicationInsightsDataClientImpl client;

    /**
     * Initializes an instance of QuerysImpl.
     *
     * @param retrofit the Retrofit instance built from a Retrofit Builder.
     * @param client the instance of the service client containing this operation class.
     */
    public QuerysImpl(Retrofit retrofit, ApplicationInsightsDataClientImpl client) {
        this.service = retrofit.create(QuerysService.class);
        this.client = client;
    }

    /**
     * The interface defining all the services for Querys to be
     * used by Retrofit to perform actually REST calls.
     */
    interface QuerysService {
        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.applicationinsights.query.Querys execute" })
        @POST("apps/{appId}/query")
        Observable<Response<ResponseBody>> execute(@Path("appId") String appId, @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.applicationinsights.io/documentation/Using-the-API/Query) is an example for using POST with an Analytics query.
     *
     * @param appId ID of the application. This is Application ID from the API Access settings 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 execute(String appId, QueryBody body) {
        return executeWithServiceResponseAsync(appId, body).toBlocking().single().body();
    }

    /**
     * Execute an Analytics query.
     * Executes an Analytics query for data. [Here](https://dev.applicationinsights.io/documentation/Using-the-API/Query) is an example for using POST with an Analytics query.
     *
     * @param appId ID of the application. This is Application ID from the API Access settings 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> executeAsync(String appId, QueryBody body, final ServiceCallback<QueryResults> serviceCallback) {
        return ServiceFuture.fromResponse(executeWithServiceResponseAsync(appId, body), serviceCallback);
    }

    /**
     * Execute an Analytics query.
     * Executes an Analytics query for data. [Here](https://dev.applicationinsights.io/documentation/Using-the-API/Query) is an example for using POST with an Analytics query.
     *
     * @param appId ID of the application. This is Application ID from the API Access settings 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> executeAsync(String appId, QueryBody body) {
        return executeWithServiceResponseAsync(appId, 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.applicationinsights.io/documentation/Using-the-API/Query) is an example for using POST with an Analytics query.
     *
     * @param appId ID of the application. This is Application ID from the API Access settings 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>> executeWithServiceResponseAsync(String appId, QueryBody body) {
        if (appId == null) {
            throw new IllegalArgumentException("Parameter appId 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.execute(appId, body, this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<QueryResults>>>() {
                @Override
                public Observable<ServiceResponse<QueryResults>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<QueryResults> clientResponse = executeDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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

}
