// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.

package tsptest.armresourceprovider.implementation;

import com.azure.core.annotation.ServiceClient;
import com.azure.core.http.HttpHeaderName;
import com.azure.core.http.HttpHeaders;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpResponse;
import com.azure.core.http.rest.Response;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.exception.ManagementError;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.management.polling.PollResult;
import com.azure.core.management.polling.PollerFactory;
import com.azure.core.management.polling.SyncPollerFactory;
import com.azure.core.util.BinaryData;
import com.azure.core.util.Context;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.polling.AsyncPollResponse;
import com.azure.core.util.polling.LongRunningOperationStatus;
import com.azure.core.util.polling.PollerFlux;
import com.azure.core.util.polling.SyncPoller;
import com.azure.core.util.serializer.SerializerAdapter;
import com.azure.core.util.serializer.SerializerEncoding;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import tsptest.armresourceprovider.fluent.ArmClient;
import tsptest.armresourceprovider.fluent.ChildExtensionResourceInterfacesClient;
import tsptest.armresourceprovider.fluent.ChildResourcesInterfacesClient;
import tsptest.armresourceprovider.fluent.CustomTemplateResourceInterfacesClient;
import tsptest.armresourceprovider.fluent.ImmutableResourceModelsClient;
import tsptest.armresourceprovider.fluent.LroNoBodiesClient;
import tsptest.armresourceprovider.fluent.ManagedMaintenanceWindowStatusOperationsClient;
import tsptest.armresourceprovider.fluent.ModelInterfaceSameNamesClient;
import tsptest.armresourceprovider.fluent.OperationsClient;
import tsptest.armresourceprovider.fluent.TopLevelArmResourceInterfacesClient;

/**
 * Initializes a new instance of the ArmClientImpl type.
 */
@ServiceClient(builder = ArmClientBuilder.class)
public final class ArmClientImpl implements ArmClient {
    /**
     * Service host.
     */
    private final String endpoint;

    /**
     * Gets Service host.
     * 
     * @return the endpoint value.
     */
    public String getEndpoint() {
        return this.endpoint;
    }

    /**
     * Version parameter.
     */
    private final String apiVersion;

    /**
     * Gets Version parameter.
     * 
     * @return the apiVersion value.
     */
    public String getApiVersion() {
        return this.apiVersion;
    }

    /**
     * The ID of the target subscription. The value must be an UUID.
     */
    private final String subscriptionId;

    /**
     * Gets The ID of the target subscription. The value must be an UUID.
     * 
     * @return the subscriptionId value.
     */
    public String getSubscriptionId() {
        return this.subscriptionId;
    }

    /**
     * The HTTP pipeline to send requests through.
     */
    private final HttpPipeline httpPipeline;

    /**
     * Gets The HTTP pipeline to send requests through.
     * 
     * @return the httpPipeline value.
     */
    public HttpPipeline getHttpPipeline() {
        return this.httpPipeline;
    }

    /**
     * The serializer to serialize an object into a string.
     */
    private final SerializerAdapter serializerAdapter;

    /**
     * Gets The serializer to serialize an object into a string.
     * 
     * @return the serializerAdapter value.
     */
    SerializerAdapter getSerializerAdapter() {
        return this.serializerAdapter;
    }

    /**
     * The default poll interval for long-running operation.
     */
    private final Duration defaultPollInterval;

    /**
     * Gets The default poll interval for long-running operation.
     * 
     * @return the defaultPollInterval value.
     */
    public Duration getDefaultPollInterval() {
        return this.defaultPollInterval;
    }

    /**
     * The ChildResourcesInterfacesClient object to access its operations.
     */
    private final ChildResourcesInterfacesClient childResourcesInterfaces;

    /**
     * Gets the ChildResourcesInterfacesClient object to access its operations.
     * 
     * @return the ChildResourcesInterfacesClient object.
     */
    public ChildResourcesInterfacesClient getChildResourcesInterfaces() {
        return this.childResourcesInterfaces;
    }

    /**
     * The TopLevelArmResourceInterfacesClient object to access its operations.
     */
    private final TopLevelArmResourceInterfacesClient topLevelArmResourceInterfaces;

    /**
     * Gets the TopLevelArmResourceInterfacesClient object to access its operations.
     * 
     * @return the TopLevelArmResourceInterfacesClient object.
     */
    public TopLevelArmResourceInterfacesClient getTopLevelArmResourceInterfaces() {
        return this.topLevelArmResourceInterfaces;
    }

    /**
     * The CustomTemplateResourceInterfacesClient object to access its operations.
     */
    private final CustomTemplateResourceInterfacesClient customTemplateResourceInterfaces;

    /**
     * Gets the CustomTemplateResourceInterfacesClient object to access its operations.
     * 
     * @return the CustomTemplateResourceInterfacesClient object.
     */
    public CustomTemplateResourceInterfacesClient getCustomTemplateResourceInterfaces() {
        return this.customTemplateResourceInterfaces;
    }

    /**
     * The OperationsClient object to access its operations.
     */
    private final OperationsClient operations;

    /**
     * Gets the OperationsClient object to access its operations.
     * 
     * @return the OperationsClient object.
     */
    public OperationsClient getOperations() {
        return this.operations;
    }

    /**
     * The ChildExtensionResourceInterfacesClient object to access its operations.
     */
    private final ChildExtensionResourceInterfacesClient childExtensionResourceInterfaces;

    /**
     * Gets the ChildExtensionResourceInterfacesClient object to access its operations.
     * 
     * @return the ChildExtensionResourceInterfacesClient object.
     */
    public ChildExtensionResourceInterfacesClient getChildExtensionResourceInterfaces() {
        return this.childExtensionResourceInterfaces;
    }

    /**
     * The ManagedMaintenanceWindowStatusOperationsClient object to access its operations.
     */
    private final ManagedMaintenanceWindowStatusOperationsClient managedMaintenanceWindowStatusOperations;

    /**
     * Gets the ManagedMaintenanceWindowStatusOperationsClient object to access its operations.
     * 
     * @return the ManagedMaintenanceWindowStatusOperationsClient object.
     */
    public ManagedMaintenanceWindowStatusOperationsClient getManagedMaintenanceWindowStatusOperations() {
        return this.managedMaintenanceWindowStatusOperations;
    }

    /**
     * The ModelInterfaceSameNamesClient object to access its operations.
     */
    private final ModelInterfaceSameNamesClient modelInterfaceSameNames;

    /**
     * Gets the ModelInterfaceSameNamesClient object to access its operations.
     * 
     * @return the ModelInterfaceSameNamesClient object.
     */
    public ModelInterfaceSameNamesClient getModelInterfaceSameNames() {
        return this.modelInterfaceSameNames;
    }

    /**
     * The ImmutableResourceModelsClient object to access its operations.
     */
    private final ImmutableResourceModelsClient immutableResourceModels;

    /**
     * Gets the ImmutableResourceModelsClient object to access its operations.
     * 
     * @return the ImmutableResourceModelsClient object.
     */
    public ImmutableResourceModelsClient getImmutableResourceModels() {
        return this.immutableResourceModels;
    }

    /**
     * The LroNoBodiesClient object to access its operations.
     */
    private final LroNoBodiesClient lroNoBodies;

    /**
     * Gets the LroNoBodiesClient object to access its operations.
     * 
     * @return the LroNoBodiesClient object.
     */
    public LroNoBodiesClient getLroNoBodies() {
        return this.lroNoBodies;
    }

    /**
     * Initializes an instance of ArmClient client.
     * 
     * @param httpPipeline The HTTP pipeline to send requests through.
     * @param serializerAdapter The serializer to serialize an object into a string.
     * @param defaultPollInterval The default poll interval for long-running operation.
     * @param environment The Azure environment.
     * @param endpoint Service host.
     * @param subscriptionId The ID of the target subscription. The value must be an UUID.
     */
    ArmClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, Duration defaultPollInterval,
        AzureEnvironment environment, String endpoint, String subscriptionId) {
        this.httpPipeline = httpPipeline;
        this.serializerAdapter = serializerAdapter;
        this.defaultPollInterval = defaultPollInterval;
        this.endpoint = endpoint;
        this.subscriptionId = subscriptionId;
        this.apiVersion = "2023-11-01";
        this.childResourcesInterfaces = new ChildResourcesInterfacesClientImpl(this);
        this.topLevelArmResourceInterfaces = new TopLevelArmResourceInterfacesClientImpl(this);
        this.customTemplateResourceInterfaces = new CustomTemplateResourceInterfacesClientImpl(this);
        this.operations = new OperationsClientImpl(this);
        this.childExtensionResourceInterfaces = new ChildExtensionResourceInterfacesClientImpl(this);
        this.managedMaintenanceWindowStatusOperations = new ManagedMaintenanceWindowStatusOperationsClientImpl(this);
        this.modelInterfaceSameNames = new ModelInterfaceSameNamesClientImpl(this);
        this.immutableResourceModels = new ImmutableResourceModelsClientImpl(this);
        this.lroNoBodies = new LroNoBodiesClientImpl(this);
    }

    /**
     * Gets default client context.
     * 
     * @return the default client context.
     */
    public Context getContext() {
        return Context.NONE;
    }

    /**
     * Merges default client context with provided context.
     * 
     * @param context the context to be merged with default client context.
     * @return the merged context.
     */
    public Context mergeContext(Context context) {
        return CoreUtils.mergeContexts(this.getContext(), context);
    }

    /**
     * Gets long running operation result.
     * 
     * @param activationResponse the response of activation operation.
     * @param httpPipeline the http pipeline.
     * @param pollResultType type of poll result.
     * @param finalResultType type of final result.
     * @param context the context shared by all requests.
     * @param <T> type of poll result.
     * @param <U> type of final result.
     * @return poller flux for poll result and final result.
     */
    public <T, U> PollerFlux<PollResult<T>, U> getLroResult(Mono<Response<Flux<ByteBuffer>>> activationResponse,
        HttpPipeline httpPipeline, Type pollResultType, Type finalResultType, Context context) {
        return PollerFactory.create(serializerAdapter, httpPipeline, pollResultType, finalResultType,
            defaultPollInterval, activationResponse, context);
    }

    /**
     * Gets long running operation result.
     * 
     * @param activationResponse the response of activation operation.
     * @param pollResultType type of poll result.
     * @param finalResultType type of final result.
     * @param context the context shared by all requests.
     * @param <T> type of poll result.
     * @param <U> type of final result.
     * @return SyncPoller for poll result and final result.
     */
    public <T, U> SyncPoller<PollResult<T>, U> getLroResult(Response<BinaryData> activationResponse,
        Type pollResultType, Type finalResultType, Context context) {
        return SyncPollerFactory.create(serializerAdapter, httpPipeline, pollResultType, finalResultType,
            defaultPollInterval, () -> activationResponse, context);
    }

    /**
     * Gets the final result, or an error, based on last async poll response.
     * 
     * @param response the last async poll response.
     * @param <T> type of poll result.
     * @param <U> type of final result.
     * @return the final result, or an error.
     */
    public <T, U> Mono<U> getLroFinalResultOrError(AsyncPollResponse<PollResult<T>, U> response) {
        if (response.getStatus() != LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
            String errorMessage;
            ManagementError managementError = null;
            HttpResponse errorResponse = null;
            PollResult.Error lroError = response.getValue().getError();
            if (lroError != null) {
                errorResponse = new HttpResponseImpl(lroError.getResponseStatusCode(), lroError.getResponseHeaders(),
                    lroError.getResponseBody());

                errorMessage = response.getValue().getError().getMessage();
                String errorBody = response.getValue().getError().getResponseBody();
                if (errorBody != null) {
                    // try to deserialize error body to ManagementError
                    try {
                        managementError = this.getSerializerAdapter()
                            .deserialize(errorBody, ManagementError.class, SerializerEncoding.JSON);
                        if (managementError.getCode() == null || managementError.getMessage() == null) {
                            managementError = null;
                        }
                    } catch (IOException | RuntimeException ioe) {
                        LOGGER.logThrowableAsWarning(ioe);
                    }
                }
            } else {
                // fallback to default error message
                errorMessage = "Long running operation failed.";
            }
            if (managementError == null) {
                // fallback to default ManagementError
                managementError = new ManagementError(response.getStatus().toString(), errorMessage);
            }
            return Mono.error(new ManagementException(errorMessage, errorResponse, managementError));
        } else {
            return response.getFinalResult();
        }
    }

    private static final class HttpResponseImpl extends HttpResponse {
        private final int statusCode;

        private final byte[] responseBody;

        private final HttpHeaders httpHeaders;

        HttpResponseImpl(int statusCode, HttpHeaders httpHeaders, String responseBody) {
            super(null);
            this.statusCode = statusCode;
            this.httpHeaders = httpHeaders;
            this.responseBody = responseBody == null ? null : responseBody.getBytes(StandardCharsets.UTF_8);
        }

        public int getStatusCode() {
            return statusCode;
        }

        public String getHeaderValue(String s) {
            return httpHeaders.getValue(HttpHeaderName.fromString(s));
        }

        public HttpHeaders getHeaders() {
            return httpHeaders;
        }

        public Flux<ByteBuffer> getBody() {
            return Flux.just(ByteBuffer.wrap(responseBody));
        }

        public Mono<byte[]> getBodyAsByteArray() {
            return Mono.just(responseBody);
        }

        public Mono<String> getBodyAsString() {
            return Mono.just(new String(responseBody, StandardCharsets.UTF_8));
        }

        public Mono<String> getBodyAsString(Charset charset) {
            return Mono.just(new String(responseBody, charset));
        }
    }

    private static final ClientLogger LOGGER = new ClientLogger(ArmClientImpl.class);
}
