/**
 * 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 com.microsoft.azure.cognitiveservices.knowledge.qnamaker.models.UpdateSettingsOptionalParameter;
import retrofit2.Retrofit;
import com.microsoft.azure.cognitiveservices.knowledge.qnamaker.EndpointSettings;
import com.google.common.base.Joiner;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.cognitiveservices.knowledge.qnamaker.models.EndpointSettingsDTO;
import com.microsoft.azure.cognitiveservices.knowledge.qnamaker.models.EndpointSettingsDTOActiveLearning;
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 com.microsoft.rest.Validator;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.PATCH;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;

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

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

    /**
     * The interface defining all the services for EndpointSettings to be
     * used by Retrofit to perform actually REST calls.
     */
    interface EndpointSettingsService {
        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.cognitiveservices.knowledge.qnamaker.EndpointSettings getSettings" })
        @GET("endpointSettings")
        Observable<Response<ResponseBody>> getSettings(@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.EndpointSettings updateSettings" })
        @PATCH("endpointSettings")
        Observable<Response<ResponseBody>> updateSettings(@Header("accept-language") String acceptLanguage, @Body EndpointSettingsDTO endpointSettingsPayload, @Header("x-ms-parameterized-host") String parameterizedHost, @Header("User-Agent") String userAgent);

    }

    /**
     * Gets endpoint settings 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 EndpointSettingsDTO object if successful.
     */
    public EndpointSettingsDTO getSettings() {
        return getSettingsWithServiceResponseAsync().toBlocking().single().body();
    }

    /**
     * Gets endpoint settings 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<EndpointSettingsDTO> getSettingsAsync(final ServiceCallback<EndpointSettingsDTO> serviceCallback) {
        return ServiceFuture.fromResponse(getSettingsWithServiceResponseAsync(), serviceCallback);
    }

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

    /**
     * Gets endpoint settings for an endpoint.
     *
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the EndpointSettingsDTO object
     */
    public Observable<ServiceResponse<EndpointSettingsDTO>> getSettingsWithServiceResponseAsync() {
        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.getSettings(this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<EndpointSettingsDTO>>>() {
                @Override
                public Observable<ServiceResponse<EndpointSettingsDTO>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<EndpointSettingsDTO> clientResponse = getSettingsDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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


    /**
     * Updates endpoint settings for an endpoint.
     *
     * @param updateSettingsOptionalParameter the object representing the optional parameters to be set before calling this API
     * @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
     */
    public void updateSettings(UpdateSettingsOptionalParameter updateSettingsOptionalParameter) {
        updateSettingsWithServiceResponseAsync(updateSettingsOptionalParameter).toBlocking().single().body();
    }

    /**
     * Updates endpoint settings for an endpoint.
     *
     * @param updateSettingsOptionalParameter the object representing the optional parameters to be set before calling this API
     * @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<Void> updateSettingsAsync(UpdateSettingsOptionalParameter updateSettingsOptionalParameter, final ServiceCallback<Void> serviceCallback) {
        return ServiceFuture.fromResponse(updateSettingsWithServiceResponseAsync(updateSettingsOptionalParameter), serviceCallback);
    }

    /**
     * Updates endpoint settings for an endpoint.
     *
     * @param updateSettingsOptionalParameter the object representing the optional parameters to be set before calling this API
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceResponse} object if successful.
     */
    public Observable<Void> updateSettingsAsync(UpdateSettingsOptionalParameter updateSettingsOptionalParameter) {
        return updateSettingsWithServiceResponseAsync(updateSettingsOptionalParameter).map(new Func1<ServiceResponse<Void>, Void>() {
            @Override
            public Void call(ServiceResponse<Void> response) {
                return response.body();
            }
        });
    }

    /**
     * Updates endpoint settings for an endpoint.
     *
     * @param updateSettingsOptionalParameter the object representing the optional parameters to be set before calling this API
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceResponse} object if successful.
     */
    public Observable<ServiceResponse<Void>> updateSettingsWithServiceResponseAsync(UpdateSettingsOptionalParameter updateSettingsOptionalParameter) {
        if (this.client.endpoint() == null) {
            throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
        }
        final EndpointSettingsDTOActiveLearning activeLearning = updateSettingsOptionalParameter != null ? updateSettingsOptionalParameter.activeLearning() : null;

        return updateSettingsWithServiceResponseAsync(activeLearning);
    }

    /**
     * Updates endpoint settings for an endpoint.
     *
     * @param activeLearning Active Learning settings of the endpoint.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceResponse} object if successful.
     */
    public Observable<ServiceResponse<Void>> updateSettingsWithServiceResponseAsync(EndpointSettingsDTOActiveLearning activeLearning) {
        if (this.client.endpoint() == null) {
            throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
        }
        Validator.validate(activeLearning);
        EndpointSettingsDTO endpointSettingsPayload = new EndpointSettingsDTO();
        endpointSettingsPayload.withActiveLearning(activeLearning);
        String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
        return service.updateSettings(this.client.acceptLanguage(), endpointSettingsPayload, parameterizedHost, this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = updateSettingsDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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

    @Override
    public EndpointSettingsUpdateSettingsParameters updateSettings() {
        return new EndpointSettingsUpdateSettingsParameters(this);
    }

    /**
     * Internal class implementing EndpointSettingsUpdateSettingsDefinition.
     */
    class EndpointSettingsUpdateSettingsParameters implements EndpointSettingsUpdateSettingsDefinition {
        private EndpointSettingsImpl parent;
        private EndpointSettingsDTOActiveLearning activeLearning;

        /**
         * Constructor.
         * @param parent the parent object.
         */
        EndpointSettingsUpdateSettingsParameters(EndpointSettingsImpl parent) {
            this.parent = parent;
        }

        @Override
        public EndpointSettingsUpdateSettingsParameters withActiveLearning(EndpointSettingsDTOActiveLearning activeLearning) {
            this.activeLearning = activeLearning;
            return this;
        }

        @Override
        public void execute() {
        updateSettingsWithServiceResponseAsync(activeLearning).toBlocking().single().body();
    }

        @Override
        public Observable<Void> executeAsync() {
            return updateSettingsWithServiceResponseAsync(activeLearning).map(new Func1<ServiceResponse<Void>, Void>() {
                @Override
                public Void call(ServiceResponse<Void> response) {
                    return response.body();
                }
            });
        }
    }

}
