//go:build go1.18
// +build go1.18

// 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. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

package armazurestackhci

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"
)

// EdgeDevicesClient contains the methods for the EdgeDevices group.
// Don't use this type directly, use NewEdgeDevicesClient() instead.
type EdgeDevicesClient struct {
	internal *arm.Client
}

// NewEdgeDevicesClient creates a new instance of EdgeDevicesClient with the specified values.
//   - credential - used to authorize requests. Usually a credential from azidentity.
//   - options - pass nil to accept the default values.
func NewEdgeDevicesClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*EdgeDevicesClient, error) {
	cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
	if err != nil {
		return nil, err
	}
	client := &EdgeDevicesClient{
		internal: cl,
	}
	return client, nil
}

// BeginCreateOrUpdate - Create a EdgeDevice
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
//   - resourceURI - The fully qualified Azure Resource manager identifier of the resource.
//   - edgeDeviceName - Name of Device
//   - resource - Resource create parameters.
//   - options - EdgeDevicesClientBeginCreateOrUpdateOptions contains the optional parameters for the EdgeDevicesClient.BeginCreateOrUpdate
//     method.
func (client *EdgeDevicesClient) BeginCreateOrUpdate(ctx context.Context, resourceURI string, edgeDeviceName string, resource EdgeDeviceClassification, options *EdgeDevicesClientBeginCreateOrUpdateOptions) (*runtime.Poller[EdgeDevicesClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, resourceURI, edgeDeviceName, resource, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[EdgeDevicesClientCreateOrUpdateResponse]{
			FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[EdgeDevicesClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Create a EdgeDevice
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
func (client *EdgeDevicesClient) createOrUpdate(ctx context.Context, resourceURI string, edgeDeviceName string, resource EdgeDeviceClassification, options *EdgeDevicesClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "EdgeDevicesClient.BeginCreateOrUpdate"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.createOrUpdateCreateRequest(ctx, resourceURI, edgeDeviceName, resource, 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
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *EdgeDevicesClient) createOrUpdateCreateRequest(ctx context.Context, resourceURI string, edgeDeviceName string, resource EdgeDeviceClassification, options *EdgeDevicesClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/{resourceUri}/providers/Microsoft.AzureStackHCI/edgeDevices/{edgeDeviceName}"
	urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI)
	if edgeDeviceName == "" {
		return nil, errors.New("parameter edgeDeviceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{edgeDeviceName}", url.PathEscape(edgeDeviceName))
	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-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, resource); err != nil {
		return nil, err
	}
	return req, nil
}

// BeginDelete - Delete a EdgeDevice
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
//   - resourceURI - The fully qualified Azure Resource manager identifier of the resource.
//   - edgeDeviceName - Name of Device
//   - options - EdgeDevicesClientBeginDeleteOptions contains the optional parameters for the EdgeDevicesClient.BeginDelete method.
func (client *EdgeDevicesClient) BeginDelete(ctx context.Context, resourceURI string, edgeDeviceName string, options *EdgeDevicesClientBeginDeleteOptions) (*runtime.Poller[EdgeDevicesClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceURI, edgeDeviceName, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[EdgeDevicesClientDeleteResponse]{
			FinalStateVia: runtime.FinalStateViaLocation,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[EdgeDevicesClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Delete a EdgeDevice
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
func (client *EdgeDevicesClient) deleteOperation(ctx context.Context, resourceURI string, edgeDeviceName string, options *EdgeDevicesClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "EdgeDevicesClient.BeginDelete"
	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, resourceURI, edgeDeviceName, 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.StatusAccepted, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// deleteCreateRequest creates the Delete request.
func (client *EdgeDevicesClient) deleteCreateRequest(ctx context.Context, resourceURI string, edgeDeviceName string, options *EdgeDevicesClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/{resourceUri}/providers/Microsoft.AzureStackHCI/edgeDevices/{edgeDeviceName}"
	urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI)
	if edgeDeviceName == "" {
		return nil, errors.New("parameter edgeDeviceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{edgeDeviceName}", url.PathEscape(edgeDeviceName))
	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-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Get a EdgeDevice
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
//   - resourceURI - The fully qualified Azure Resource manager identifier of the resource.
//   - edgeDeviceName - Name of Device
//   - options - EdgeDevicesClientGetOptions contains the optional parameters for the EdgeDevicesClient.Get method.
func (client *EdgeDevicesClient) Get(ctx context.Context, resourceURI string, edgeDeviceName string, options *EdgeDevicesClientGetOptions) (EdgeDevicesClientGetResponse, error) {
	var err error
	const operationName = "EdgeDevicesClient.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, resourceURI, edgeDeviceName, options)
	if err != nil {
		return EdgeDevicesClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return EdgeDevicesClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return EdgeDevicesClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *EdgeDevicesClient) getCreateRequest(ctx context.Context, resourceURI string, edgeDeviceName string, options *EdgeDevicesClientGetOptions) (*policy.Request, error) {
	urlPath := "/{resourceUri}/providers/Microsoft.AzureStackHCI/edgeDevices/{edgeDeviceName}"
	urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI)
	if edgeDeviceName == "" {
		return nil, errors.New("parameter edgeDeviceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{edgeDeviceName}", url.PathEscape(edgeDeviceName))
	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-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// NewListPager - List EdgeDevice resources by parent
//
// Generated from API version 2024-04-01
//   - resourceURI - The fully qualified Azure Resource manager identifier of the resource.
//   - options - EdgeDevicesClientListOptions contains the optional parameters for the EdgeDevicesClient.NewListPager method.
func (client *EdgeDevicesClient) NewListPager(resourceURI string, options *EdgeDevicesClientListOptions) *runtime.Pager[EdgeDevicesClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[EdgeDevicesClientListResponse]{
		More: func(page EdgeDevicesClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *EdgeDevicesClientListResponse) (EdgeDevicesClientListResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "EdgeDevicesClient.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, resourceURI, options)
			}, nil)
			if err != nil {
				return EdgeDevicesClientListResponse{}, err
			}
			return client.listHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listCreateRequest creates the List request.
func (client *EdgeDevicesClient) listCreateRequest(ctx context.Context, resourceURI string, options *EdgeDevicesClientListOptions) (*policy.Request, error) {
	urlPath := "/{resourceUri}/providers/Microsoft.AzureStackHCI/edgeDevices"
	urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI)
	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-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// BeginValidate - A long-running resource action.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
//   - resourceURI - The fully qualified Azure Resource manager identifier of the resource.
//   - edgeDeviceName - Name of Device
//   - validateRequest - The content of the action request
//   - options - EdgeDevicesClientBeginValidateOptions contains the optional parameters for the EdgeDevicesClient.BeginValidate
//     method.
func (client *EdgeDevicesClient) BeginValidate(ctx context.Context, resourceURI string, edgeDeviceName string, validateRequest ValidateRequest, options *EdgeDevicesClientBeginValidateOptions) (*runtime.Poller[EdgeDevicesClientValidateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.validate(ctx, resourceURI, edgeDeviceName, validateRequest, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[EdgeDevicesClientValidateResponse]{
			FinalStateVia: runtime.FinalStateViaLocation,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[EdgeDevicesClientValidateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Validate - A long-running resource action.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-04-01
func (client *EdgeDevicesClient) validate(ctx context.Context, resourceURI string, edgeDeviceName string, validateRequest ValidateRequest, options *EdgeDevicesClientBeginValidateOptions) (*http.Response, error) {
	var err error
	const operationName = "EdgeDevicesClient.BeginValidate"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.validateCreateRequest(ctx, resourceURI, edgeDeviceName, validateRequest, 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.StatusAccepted) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// validateCreateRequest creates the Validate request.
func (client *EdgeDevicesClient) validateCreateRequest(ctx context.Context, resourceURI string, edgeDeviceName string, validateRequest ValidateRequest, options *EdgeDevicesClientBeginValidateOptions) (*policy.Request, error) {
	urlPath := "/{resourceUri}/providers/Microsoft.AzureStackHCI/edgeDevices/{edgeDeviceName}/validate"
	urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI)
	if edgeDeviceName == "" {
		return nil, errors.New("parameter edgeDeviceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{edgeDeviceName}", url.PathEscape(edgeDeviceName))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2024-04-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, validateRequest); err != nil {
		return nil, err
	}
	return req, nil
}
