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

package com.azure.resourcemanager.applicationinsights.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.applicationinsights.fluent.AnalyticsItemsClient;
import com.azure.resourcemanager.applicationinsights.fluent.AnnotationsClient;
import com.azure.resourcemanager.applicationinsights.fluent.ApiKeysClient;
import com.azure.resourcemanager.applicationinsights.fluent.ApplicationInsightsManagementClient;
import com.azure.resourcemanager.applicationinsights.fluent.ComponentAvailableFeaturesClient;
import com.azure.resourcemanager.applicationinsights.fluent.ComponentCurrentBillingFeaturesClient;
import com.azure.resourcemanager.applicationinsights.fluent.ComponentFeatureCapabilitiesClient;
import com.azure.resourcemanager.applicationinsights.fluent.ComponentLinkedStorageAccountsOperationsClient;
import com.azure.resourcemanager.applicationinsights.fluent.ComponentQuotaStatusClient;
import com.azure.resourcemanager.applicationinsights.fluent.ComponentsClient;
import com.azure.resourcemanager.applicationinsights.fluent.ExportConfigurationsClient;
import com.azure.resourcemanager.applicationinsights.fluent.FavoritesClient;
import com.azure.resourcemanager.applicationinsights.fluent.LiveTokensClient;
import com.azure.resourcemanager.applicationinsights.fluent.MyWorkbooksClient;
import com.azure.resourcemanager.applicationinsights.fluent.OperationsClient;
import com.azure.resourcemanager.applicationinsights.fluent.ProactiveDetectionConfigurationsClient;
import com.azure.resourcemanager.applicationinsights.fluent.WebTestLocationsClient;
import com.azure.resourcemanager.applicationinsights.fluent.WebTestsClient;
import com.azure.resourcemanager.applicationinsights.fluent.WorkItemConfigurationsClient;
import com.azure.resourcemanager.applicationinsights.fluent.WorkbookTemplatesClient;
import com.azure.resourcemanager.applicationinsights.fluent.WorkbooksClient;
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 ApplicationInsightsManagementClientImpl type. */
@ServiceClient(builder = ApplicationInsightsManagementClientBuilder.class)
public final class ApplicationInsightsManagementClientImpl implements ApplicationInsightsManagementClient {
    /** The ID of the target subscription. */
    private final String subscriptionId;

    /**
     * Gets The ID of the target subscription.
     *
     * @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;
    }

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

    /**
     * Gets the AnnotationsClient object to access its operations.
     *
     * @return the AnnotationsClient object.
     */
    public AnnotationsClient getAnnotations() {
        return this.annotations;
    }

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

    /**
     * Gets the ApiKeysClient object to access its operations.
     *
     * @return the ApiKeysClient object.
     */
    public ApiKeysClient getApiKeys() {
        return this.apiKeys;
    }

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

    /**
     * Gets the ExportConfigurationsClient object to access its operations.
     *
     * @return the ExportConfigurationsClient object.
     */
    public ExportConfigurationsClient getExportConfigurations() {
        return this.exportConfigurations;
    }

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

    /**
     * Gets the ComponentCurrentBillingFeaturesClient object to access its operations.
     *
     * @return the ComponentCurrentBillingFeaturesClient object.
     */
    public ComponentCurrentBillingFeaturesClient getComponentCurrentBillingFeatures() {
        return this.componentCurrentBillingFeatures;
    }

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

    /**
     * Gets the ComponentQuotaStatusClient object to access its operations.
     *
     * @return the ComponentQuotaStatusClient object.
     */
    public ComponentQuotaStatusClient getComponentQuotaStatus() {
        return this.componentQuotaStatus;
    }

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

    /**
     * Gets the ComponentFeatureCapabilitiesClient object to access its operations.
     *
     * @return the ComponentFeatureCapabilitiesClient object.
     */
    public ComponentFeatureCapabilitiesClient getComponentFeatureCapabilities() {
        return this.componentFeatureCapabilities;
    }

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

    /**
     * Gets the ComponentAvailableFeaturesClient object to access its operations.
     *
     * @return the ComponentAvailableFeaturesClient object.
     */
    public ComponentAvailableFeaturesClient getComponentAvailableFeatures() {
        return this.componentAvailableFeatures;
    }

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

    /**
     * Gets the ProactiveDetectionConfigurationsClient object to access its operations.
     *
     * @return the ProactiveDetectionConfigurationsClient object.
     */
    public ProactiveDetectionConfigurationsClient getProactiveDetectionConfigurations() {
        return this.proactiveDetectionConfigurations;
    }

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

    /**
     * Gets the WorkItemConfigurationsClient object to access its operations.
     *
     * @return the WorkItemConfigurationsClient object.
     */
    public WorkItemConfigurationsClient getWorkItemConfigurations() {
        return this.workItemConfigurations;
    }

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

    /**
     * Gets the FavoritesClient object to access its operations.
     *
     * @return the FavoritesClient object.
     */
    public FavoritesClient getFavorites() {
        return this.favorites;
    }

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

    /**
     * Gets the WebTestLocationsClient object to access its operations.
     *
     * @return the WebTestLocationsClient object.
     */
    public WebTestLocationsClient getWebTestLocations() {
        return this.webTestLocations;
    }

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

    /**
     * Gets the WebTestsClient object to access its operations.
     *
     * @return the WebTestsClient object.
     */
    public WebTestsClient getWebTests() {
        return this.webTests;
    }

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

    /**
     * Gets the AnalyticsItemsClient object to access its operations.
     *
     * @return the AnalyticsItemsClient object.
     */
    public AnalyticsItemsClient getAnalyticsItems() {
        return this.analyticsItems;
    }

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

    /**
     * Gets the WorkbookTemplatesClient object to access its operations.
     *
     * @return the WorkbookTemplatesClient object.
     */
    public WorkbookTemplatesClient getWorkbookTemplates() {
        return this.workbookTemplates;
    }

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

    /**
     * Gets the MyWorkbooksClient object to access its operations.
     *
     * @return the MyWorkbooksClient object.
     */
    public MyWorkbooksClient getMyWorkbooks() {
        return this.myWorkbooks;
    }

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

    /**
     * Gets the WorkbooksClient object to access its operations.
     *
     * @return the WorkbooksClient object.
     */
    public WorkbooksClient getWorkbooks() {
        return this.workbooks;
    }

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

    /**
     * Gets the ComponentsClient object to access its operations.
     *
     * @return the ComponentsClient object.
     */
    public ComponentsClient getComponents() {
        return this.components;
    }

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

    /**
     * Gets the ComponentLinkedStorageAccountsOperationsClient object to access its operations.
     *
     * @return the ComponentLinkedStorageAccountsOperationsClient object.
     */
    public ComponentLinkedStorageAccountsOperationsClient getComponentLinkedStorageAccountsOperations() {
        return this.componentLinkedStorageAccountsOperations;
    }

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

    /**
     * Gets the LiveTokensClient object to access its operations.
     *
     * @return the LiveTokensClient object.
     */
    public LiveTokensClient getLiveTokens() {
        return this.liveTokens;
    }

    /**
     * Initializes an instance of ApplicationInsightsManagementClient 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.
     * @param endpoint server parameter.
     */
    ApplicationInsightsManagementClientImpl(
        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.operations = new OperationsClientImpl(this);
        this.annotations = new AnnotationsClientImpl(this);
        this.apiKeys = new ApiKeysClientImpl(this);
        this.exportConfigurations = new ExportConfigurationsClientImpl(this);
        this.componentCurrentBillingFeatures = new ComponentCurrentBillingFeaturesClientImpl(this);
        this.componentQuotaStatus = new ComponentQuotaStatusClientImpl(this);
        this.componentFeatureCapabilities = new ComponentFeatureCapabilitiesClientImpl(this);
        this.componentAvailableFeatures = new ComponentAvailableFeaturesClientImpl(this);
        this.proactiveDetectionConfigurations = new ProactiveDetectionConfigurationsClientImpl(this);
        this.workItemConfigurations = new WorkItemConfigurationsClientImpl(this);
        this.favorites = new FavoritesClientImpl(this);
        this.webTestLocations = new WebTestLocationsClientImpl(this);
        this.webTests = new WebTestsClientImpl(this);
        this.analyticsItems = new AnalyticsItemsClientImpl(this);
        this.workbookTemplates = new WorkbookTemplatesClientImpl(this);
        this.myWorkbooks = new MyWorkbooksClientImpl(this);
        this.workbooks = new WorkbooksClientImpl(this);
        this.components = new ComponentsClientImpl(this);
        this.componentLinkedStorageAccountsOperations = new ComponentLinkedStorageAccountsOperationsClientImpl(this);
        this.liveTokens = new LiveTokensClientImpl(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(ApplicationInsightsManagementClientImpl.class);
}
