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

package com.azure.resourcemanager.networkcloud.implementation;

import com.azure.core.annotation.ServiceClient;
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.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.serializer.SerializerAdapter;
import com.azure.core.util.serializer.SerializerEncoding;
import com.azure.resourcemanager.networkcloud.fluent.AgentPoolsClient;
import com.azure.resourcemanager.networkcloud.fluent.BareMetalMachineKeySetsClient;
import com.azure.resourcemanager.networkcloud.fluent.BareMetalMachinesClient;
import com.azure.resourcemanager.networkcloud.fluent.BmcKeySetsClient;
import com.azure.resourcemanager.networkcloud.fluent.CloudServicesNetworksClient;
import com.azure.resourcemanager.networkcloud.fluent.ClusterManagersClient;
import com.azure.resourcemanager.networkcloud.fluent.ClustersClient;
import com.azure.resourcemanager.networkcloud.fluent.ConsolesClient;
import com.azure.resourcemanager.networkcloud.fluent.KubernetesClustersClient;
import com.azure.resourcemanager.networkcloud.fluent.L2NetworksClient;
import com.azure.resourcemanager.networkcloud.fluent.L3NetworksClient;
import com.azure.resourcemanager.networkcloud.fluent.MetricsConfigurationsClient;
import com.azure.resourcemanager.networkcloud.fluent.NetworkCloud;
import com.azure.resourcemanager.networkcloud.fluent.OperationsClient;
import com.azure.resourcemanager.networkcloud.fluent.RackSkusClient;
import com.azure.resourcemanager.networkcloud.fluent.RacksClient;
import com.azure.resourcemanager.networkcloud.fluent.StorageAppliancesClient;
import com.azure.resourcemanager.networkcloud.fluent.TrunkedNetworksClient;
import com.azure.resourcemanager.networkcloud.fluent.VirtualMachinesClient;
import com.azure.resourcemanager.networkcloud.fluent.VolumesClient;
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;

/** Initializes a new instance of the NetworkCloudImpl type. */
@ServiceClient(builder = NetworkCloudBuilder.class)
public final class NetworkCloudImpl implements NetworkCloud {
    /** 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;
    }

    /** server parameter. */
    private final String endpoint;

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

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

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

    /** 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 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 BareMetalMachinesClient object to access its operations. */
    private final BareMetalMachinesClient bareMetalMachines;

    /**
     * Gets the BareMetalMachinesClient object to access its operations.
     *
     * @return the BareMetalMachinesClient object.
     */
    public BareMetalMachinesClient getBareMetalMachines() {
        return this.bareMetalMachines;
    }

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

    /**
     * Gets the CloudServicesNetworksClient object to access its operations.
     *
     * @return the CloudServicesNetworksClient object.
     */
    public CloudServicesNetworksClient getCloudServicesNetworks() {
        return this.cloudServicesNetworks;
    }

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

    /**
     * Gets the ClusterManagersClient object to access its operations.
     *
     * @return the ClusterManagersClient object.
     */
    public ClusterManagersClient getClusterManagers() {
        return this.clusterManagers;
    }

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

    /**
     * Gets the ClustersClient object to access its operations.
     *
     * @return the ClustersClient object.
     */
    public ClustersClient getClusters() {
        return this.clusters;
    }

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

    /**
     * Gets the KubernetesClustersClient object to access its operations.
     *
     * @return the KubernetesClustersClient object.
     */
    public KubernetesClustersClient getKubernetesClusters() {
        return this.kubernetesClusters;
    }

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

    /**
     * Gets the L2NetworksClient object to access its operations.
     *
     * @return the L2NetworksClient object.
     */
    public L2NetworksClient getL2Networks() {
        return this.l2Networks;
    }

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

    /**
     * Gets the L3NetworksClient object to access its operations.
     *
     * @return the L3NetworksClient object.
     */
    public L3NetworksClient getL3Networks() {
        return this.l3Networks;
    }

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

    /**
     * Gets the RackSkusClient object to access its operations.
     *
     * @return the RackSkusClient object.
     */
    public RackSkusClient getRackSkus() {
        return this.rackSkus;
    }

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

    /**
     * Gets the RacksClient object to access its operations.
     *
     * @return the RacksClient object.
     */
    public RacksClient getRacks() {
        return this.racks;
    }

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

    /**
     * Gets the StorageAppliancesClient object to access its operations.
     *
     * @return the StorageAppliancesClient object.
     */
    public StorageAppliancesClient getStorageAppliances() {
        return this.storageAppliances;
    }

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

    /**
     * Gets the TrunkedNetworksClient object to access its operations.
     *
     * @return the TrunkedNetworksClient object.
     */
    public TrunkedNetworksClient getTrunkedNetworks() {
        return this.trunkedNetworks;
    }

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

    /**
     * Gets the VirtualMachinesClient object to access its operations.
     *
     * @return the VirtualMachinesClient object.
     */
    public VirtualMachinesClient getVirtualMachines() {
        return this.virtualMachines;
    }

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

    /**
     * Gets the VolumesClient object to access its operations.
     *
     * @return the VolumesClient object.
     */
    public VolumesClient getVolumes() {
        return this.volumes;
    }

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

    /**
     * Gets the BareMetalMachineKeySetsClient object to access its operations.
     *
     * @return the BareMetalMachineKeySetsClient object.
     */
    public BareMetalMachineKeySetsClient getBareMetalMachineKeySets() {
        return this.bareMetalMachineKeySets;
    }

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

    /**
     * Gets the BmcKeySetsClient object to access its operations.
     *
     * @return the BmcKeySetsClient object.
     */
    public BmcKeySetsClient getBmcKeySets() {
        return this.bmcKeySets;
    }

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

    /**
     * Gets the MetricsConfigurationsClient object to access its operations.
     *
     * @return the MetricsConfigurationsClient object.
     */
    public MetricsConfigurationsClient getMetricsConfigurations() {
        return this.metricsConfigurations;
    }

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

    /**
     * Gets the AgentPoolsClient object to access its operations.
     *
     * @return the AgentPoolsClient object.
     */
    public AgentPoolsClient getAgentPools() {
        return this.agentPools;
    }

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

    /**
     * Gets the ConsolesClient object to access its operations.
     *
     * @return the ConsolesClient object.
     */
    public ConsolesClient getConsoles() {
        return this.consoles;
    }

    /**
     * Initializes an instance of NetworkCloud 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 subscriptionId The ID of the target subscription. The value must be an UUID.
     * @param endpoint server parameter.
     */
    NetworkCloudImpl(
        HttpPipeline httpPipeline,
        SerializerAdapter serializerAdapter,
        Duration defaultPollInterval,
        AzureEnvironment environment,
        String subscriptionId,
        String endpoint) {
        this.httpPipeline = httpPipeline;
        this.serializerAdapter = serializerAdapter;
        this.defaultPollInterval = defaultPollInterval;
        this.subscriptionId = subscriptionId;
        this.endpoint = endpoint;
        this.apiVersion = "2023-05-01-preview";
        this.operations = new OperationsClientImpl(this);
        this.bareMetalMachines = new BareMetalMachinesClientImpl(this);
        this.cloudServicesNetworks = new CloudServicesNetworksClientImpl(this);
        this.clusterManagers = new ClusterManagersClientImpl(this);
        this.clusters = new ClustersClientImpl(this);
        this.kubernetesClusters = new KubernetesClustersClientImpl(this);
        this.l2Networks = new L2NetworksClientImpl(this);
        this.l3Networks = new L3NetworksClientImpl(this);
        this.rackSkus = new RackSkusClientImpl(this);
        this.racks = new RacksClientImpl(this);
        this.storageAppliances = new StorageAppliancesClientImpl(this);
        this.trunkedNetworks = new TrunkedNetworksClientImpl(this);
        this.virtualMachines = new VirtualMachinesClientImpl(this);
        this.volumes = new VolumesClientImpl(this);
        this.bareMetalMachineKeySets = new BareMetalMachineKeySetsClientImpl(this);
        this.bmcKeySets = new BmcKeySetsClientImpl(this);
        this.metricsConfigurations = new MetricsConfigurationsClientImpl(this);
        this.agentPools = new AgentPoolsClientImpl(this);
        this.consoles = new ConsolesClientImpl(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 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(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(NetworkCloudImpl.class);
}
