/**
 * 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.cognitiveservices.knowledge.qnamaker.implementation;

import retrofit2.Retrofit;
import com.microsoft.azure.cognitiveservices.knowledge.qnamaker.EndpointKeys;
import com.google.common.base.Joiner;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.cognitiveservices.knowledge.qnamaker.models.EndpointKeysDTO;
import com.microsoft.azure.cognitiveservices.knowledge.qnamaker.models.ErrorResponseException;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.PATCH;
import retrofit2.http.Path;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;

/**
 * An instance of this class provides access to all the operations defined
 * in EndpointKeys.
 */
public class EndpointKeysImpl implements EndpointKeys {
    /** The Retrofit service to perform REST calls. */
    private EndpointKeysService service;
    /** The service client containing this operation class. */
    private QnAMakerClientImpl client;

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

    /**
     * The interface defining all the services for EndpointKeys to be
     * used by Retrofit to perform actually REST calls.
     */
    interface EndpointKeysService {
        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.cognitiveservices.knowledge.qnamaker.EndpointKeys getKeys" })
        @GET("endpointkeys")
        Observable<Response<ResponseBody>> getKeys(@Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.cognitiveservices.knowledge.qnamaker.EndpointKeys refreshKeys" })
        @PATCH("endpointkeys/{keyType}")
        Observable<Response<ResponseBody>> refreshKeys(@Path("keyType") String keyType, @Header("accept-language") String acceptLanguage, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent);

    }

    /**
     * Gets endpoint keys for an endpoint.
     *
     * @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 EndpointKeysDTO object if successful.
     */
    public EndpointKeysDTO getKeys() {
        return getKeysWithServiceResponseAsync().toBlocking().single().body();
    }

    /**
     * Gets endpoint keys for an endpoint.
     *
     * @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<EndpointKeysDTO> getKeysAsync(final ServiceCallback<EndpointKeysDTO> serviceCallback) {
        return ServiceFuture.fromResponse(getKeysWithServiceResponseAsync(), serviceCallback);
    }

    /**
     * Gets endpoint keys for an endpoint.
     *
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the EndpointKeysDTO object
     */
    public Observable<EndpointKeysDTO> getKeysAsync() {
        return getKeysWithServiceResponseAsync().map(new Func1<ServiceResponse<EndpointKeysDTO>, EndpointKeysDTO>() {
            @Override
            public EndpointKeysDTO call(ServiceResponse<EndpointKeysDTO> response) {
                return response.body();
            }
        });
    }

    /**
     * Gets endpoint keys for an endpoint.
     *
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the EndpointKeysDTO object
     */
    public Observable<ServiceResponse<EndpointKeysDTO>> getKeysWithServiceResponseAsync() {
        if (this.client.endpoint() == null) {
            throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
        }
        String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
        return service.getKeys(this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<EndpointKeysDTO>>>() {
                @Override
                public Observable<ServiceResponse<EndpointKeysDTO>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<EndpointKeysDTO> clientResponse = getKeysDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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

    /**
     * Re-generates an endpoint key.
     *
     * @param keyType Type of Key
     * @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 EndpointKeysDTO object if successful.
     */
    public EndpointKeysDTO refreshKeys(String keyType) {
        return refreshKeysWithServiceResponseAsync(keyType).toBlocking().single().body();
    }

    /**
     * Re-generates an endpoint key.
     *
     * @param keyType Type of Key
     * @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<EndpointKeysDTO> refreshKeysAsync(String keyType, final ServiceCallback<EndpointKeysDTO> serviceCallback) {
        return ServiceFuture.fromResponse(refreshKeysWithServiceResponseAsync(keyType), serviceCallback);
    }

    /**
     * Re-generates an endpoint key.
     *
     * @param keyType Type of Key
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the EndpointKeysDTO object
     */
    public Observable<EndpointKeysDTO> refreshKeysAsync(String keyType) {
        return refreshKeysWithServiceResponseAsync(keyType).map(new Func1<ServiceResponse<EndpointKeysDTO>, EndpointKeysDTO>() {
            @Override
            public EndpointKeysDTO call(ServiceResponse<EndpointKeysDTO> response) {
                return response.body();
            }
        });
    }

    /**
     * Re-generates an endpoint key.
     *
     * @param keyType Type of Key
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the EndpointKeysDTO object
     */
    public Observable<ServiceResponse<EndpointKeysDTO>> refreshKeysWithServiceResponseAsync(String keyType) {
        if (this.client.endpoint() == null) {
            throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
        }
        if (keyType == null) {
            throw new IllegalArgumentException("Parameter keyType is required and cannot be null.");
        }
        String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
        return service.refreshKeys(keyType, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<EndpointKeysDTO>>>() {
                @Override
                public Observable<ServiceResponse<EndpointKeysDTO>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<EndpointKeysDTO> clientResponse = refreshKeysDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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

}
