// 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) Go Code Generator. DO NOT EDIT.

package armdashboard

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// ManagedDashboardsClient contains the methods for the ManagedDashboards group.
// Don't use this type directly, use NewManagedDashboardsClient() instead.
type ManagedDashboardsClient struct {
	internal       *arm.Client
	subscriptionID string
}

// NewManagedDashboardsClient creates a new instance of ManagedDashboardsClient with the specified values.
//   - subscriptionID - The ID of the target subscription. The value must be an UUID.
//   - credential - used to authorize requests. Usually a credential from azidentity.
//   - options - pass nil to accept the default values.
func NewManagedDashboardsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ManagedDashboardsClient, error) {
	cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
	if err != nil {
		return nil, err
	}
	client := &ManagedDashboardsClient{
		subscriptionID: subscriptionID,
		internal:       cl,
	}
	return client, nil
}

// BeginCreate - Create or update a dashboard for grafana resource. This API is idempotent, so user can either create a new
// dashboard or update an existing dashboard.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-11-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - dashboardName - The name of the Azure Managed Dashboard.
//   - options - ManagedDashboardsClientBeginCreateOptions contains the optional parameters for the ManagedDashboardsClient.BeginCreate
//     method.
func (client *ManagedDashboardsClient) BeginCreate(ctx context.Context, resourceGroupName string, dashboardName string, requestBodyParameters ManagedDashboard, options *ManagedDashboardsClientBeginCreateOptions) (*runtime.Poller[ManagedDashboardsClientCreateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.create(ctx, resourceGroupName, dashboardName, requestBodyParameters, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ManagedDashboardsClientCreateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ManagedDashboardsClientCreateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Create - Create or update a dashboard for grafana resource. This API is idempotent, so user can either create a new dashboard
// or update an existing dashboard.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-11-01-preview
func (client *ManagedDashboardsClient) create(ctx context.Context, resourceGroupName string, dashboardName string, requestBodyParameters ManagedDashboard, options *ManagedDashboardsClientBeginCreateOptions) (*http.Response, error) {
	var err error
	const operationName = "ManagedDashboardsClient.BeginCreate"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.createCreateRequest(ctx, resourceGroupName, dashboardName, requestBodyParameters, options)
	if err != nil {
		return nil, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// createCreateRequest creates the Create request.
func (client *ManagedDashboardsClient) createCreateRequest(ctx context.Context, resourceGroupName string, dashboardName string, requestBodyParameters ManagedDashboard, _ *ManagedDashboardsClientBeginCreateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if dashboardName == "" {
		return nil, errors.New("parameter dashboardName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{dashboardName}", url.PathEscape(dashboardName))
	req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	req.Raw().Header["Content-Type"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, requestBodyParameters); err != nil {
		return nil, err
	}
	return req, nil
}

// Delete - Delete a dashboard for Grafana resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-11-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - dashboardName - The name of the Azure Managed Dashboard.
//   - options - ManagedDashboardsClientDeleteOptions contains the optional parameters for the ManagedDashboardsClient.Delete
//     method.
func (client *ManagedDashboardsClient) Delete(ctx context.Context, resourceGroupName string, dashboardName string, options *ManagedDashboardsClientDeleteOptions) (ManagedDashboardsClientDeleteResponse, error) {
	var err error
	const operationName = "ManagedDashboardsClient.Delete"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.deleteCreateRequest(ctx, resourceGroupName, dashboardName, options)
	if err != nil {
		return ManagedDashboardsClientDeleteResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return ManagedDashboardsClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return ManagedDashboardsClientDeleteResponse{}, err
	}
	return ManagedDashboardsClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *ManagedDashboardsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, dashboardName string, _ *ManagedDashboardsClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if dashboardName == "" {
		return nil, errors.New("parameter dashboardName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{dashboardName}", url.PathEscape(dashboardName))
	req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	return req, nil
}

// Get - Get the properties of a specific dashboard for grafana resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-11-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - dashboardName - The name of the Azure Managed Dashboard.
//   - options - ManagedDashboardsClientGetOptions contains the optional parameters for the ManagedDashboardsClient.Get method.
func (client *ManagedDashboardsClient) Get(ctx context.Context, resourceGroupName string, dashboardName string, options *ManagedDashboardsClientGetOptions) (ManagedDashboardsClientGetResponse, error) {
	var err error
	const operationName = "ManagedDashboardsClient.Get"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.getCreateRequest(ctx, resourceGroupName, dashboardName, options)
	if err != nil {
		return ManagedDashboardsClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return ManagedDashboardsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return ManagedDashboardsClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *ManagedDashboardsClient) getCreateRequest(ctx context.Context, resourceGroupName string, dashboardName string, _ *ManagedDashboardsClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if dashboardName == "" {
		return nil, errors.New("parameter dashboardName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{dashboardName}", url.PathEscape(dashboardName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *ManagedDashboardsClient) getHandleResponse(resp *http.Response) (ManagedDashboardsClientGetResponse, error) {
	result := ManagedDashboardsClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ManagedDashboard); err != nil {
		return ManagedDashboardsClientGetResponse{}, err
	}
	return result, nil
}

// NewListPager - List all resources of dashboards under the specified resource group.
//
// Generated from API version 2024-11-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - options - ManagedDashboardsClientListOptions contains the optional parameters for the ManagedDashboardsClient.NewListPager
//     method.
func (client *ManagedDashboardsClient) NewListPager(resourceGroupName string, options *ManagedDashboardsClientListOptions) *runtime.Pager[ManagedDashboardsClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[ManagedDashboardsClientListResponse]{
		More: func(page ManagedDashboardsClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *ManagedDashboardsClientListResponse) (ManagedDashboardsClientListResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ManagedDashboardsClient.NewListPager")
			nextLink := ""
			if page != nil {
				nextLink = *page.NextLink
			}
			resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
				return client.listCreateRequest(ctx, resourceGroupName, options)
			}, nil)
			if err != nil {
				return ManagedDashboardsClientListResponse{}, err
			}
			return client.listHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listCreateRequest creates the List request.
func (client *ManagedDashboardsClient) listCreateRequest(ctx context.Context, resourceGroupName string, _ *ManagedDashboardsClientListOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listHandleResponse handles the List response.
func (client *ManagedDashboardsClient) listHandleResponse(resp *http.Response) (ManagedDashboardsClientListResponse, error) {
	result := ManagedDashboardsClientListResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ManagedDashboardListResponse); err != nil {
		return ManagedDashboardsClientListResponse{}, err
	}
	return result, nil
}

// NewListBySubscriptionPager - List all resources of dashboards under the specified subscription.
//
// Generated from API version 2024-11-01-preview
//   - options - ManagedDashboardsClientListBySubscriptionOptions contains the optional parameters for the ManagedDashboardsClient.NewListBySubscriptionPager
//     method.
func (client *ManagedDashboardsClient) NewListBySubscriptionPager(options *ManagedDashboardsClientListBySubscriptionOptions) *runtime.Pager[ManagedDashboardsClientListBySubscriptionResponse] {
	return runtime.NewPager(runtime.PagingHandler[ManagedDashboardsClientListBySubscriptionResponse]{
		More: func(page ManagedDashboardsClientListBySubscriptionResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *ManagedDashboardsClientListBySubscriptionResponse) (ManagedDashboardsClientListBySubscriptionResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ManagedDashboardsClient.NewListBySubscriptionPager")
			nextLink := ""
			if page != nil {
				nextLink = *page.NextLink
			}
			resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
				return client.listBySubscriptionCreateRequest(ctx, options)
			}, nil)
			if err != nil {
				return ManagedDashboardsClientListBySubscriptionResponse{}, err
			}
			return client.listBySubscriptionHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listBySubscriptionCreateRequest creates the ListBySubscription request.
func (client *ManagedDashboardsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *ManagedDashboardsClientListBySubscriptionOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Dashboard/dashboards"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listBySubscriptionHandleResponse handles the ListBySubscription response.
func (client *ManagedDashboardsClient) listBySubscriptionHandleResponse(resp *http.Response) (ManagedDashboardsClientListBySubscriptionResponse, error) {
	result := ManagedDashboardsClientListBySubscriptionResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ManagedDashboardListResponse); err != nil {
		return ManagedDashboardsClientListBySubscriptionResponse{}, err
	}
	return result, nil
}

// Update - Update a dashboard for Grafana resource.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-11-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - dashboardName - The name of the Azure Managed Dashboard.
//   - options - ManagedDashboardsClientUpdateOptions contains the optional parameters for the ManagedDashboardsClient.Update
//     method.
func (client *ManagedDashboardsClient) Update(ctx context.Context, resourceGroupName string, dashboardName string, requestBodyParameters ManagedDashboardUpdateParameters, options *ManagedDashboardsClientUpdateOptions) (ManagedDashboardsClientUpdateResponse, error) {
	var err error
	const operationName = "ManagedDashboardsClient.Update"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.updateCreateRequest(ctx, resourceGroupName, dashboardName, requestBodyParameters, options)
	if err != nil {
		return ManagedDashboardsClientUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return ManagedDashboardsClientUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return ManagedDashboardsClientUpdateResponse{}, err
	}
	resp, err := client.updateHandleResponse(httpResp)
	return resp, err
}

// updateCreateRequest creates the Update request.
func (client *ManagedDashboardsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, dashboardName string, requestBodyParameters ManagedDashboardUpdateParameters, _ *ManagedDashboardsClientUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if dashboardName == "" {
		return nil, errors.New("parameter dashboardName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{dashboardName}", url.PathEscape(dashboardName))
	req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-11-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	req.Raw().Header["Content-Type"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, requestBodyParameters); err != nil {
		return nil, err
	}
	return req, nil
}

// updateHandleResponse handles the Update response.
func (client *ManagedDashboardsClient) updateHandleResponse(resp *http.Response) (ManagedDashboardsClientUpdateResponse, error) {
	result := ManagedDashboardsClientUpdateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ManagedDashboard); err != nil {
		return ManagedDashboardsClientUpdateResponse{}, err
	}
	return result, nil
}
