//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 armhybridcontainerservice

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

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

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

// BeginCreateOrUpdate - Creates or updates the agent pool in the provisioned cluster
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-01-01
//   - connectedClusterResourceURI - The fully qualified Azure Resource Manager identifier of the connected cluster resource.
//   - agentPoolName - Parameter for the name of the agent pool in the provisioned cluster.
//   - agentPool - Agent Pool resource definition
//   - options - AgentPoolClientBeginCreateOrUpdateOptions contains the optional parameters for the AgentPoolClient.BeginCreateOrUpdate
//     method.
func (client *AgentPoolClient) BeginCreateOrUpdate(ctx context.Context, connectedClusterResourceURI string, agentPoolName string, agentPool AgentPool, options *AgentPoolClientBeginCreateOrUpdateOptions) (*runtime.Poller[AgentPoolClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, connectedClusterResourceURI, agentPoolName, agentPool, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AgentPoolClientCreateOrUpdateResponse]{
			FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AgentPoolClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Creates or updates the agent pool in the provisioned cluster
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-01-01
func (client *AgentPoolClient) createOrUpdate(ctx context.Context, connectedClusterResourceURI string, agentPoolName string, agentPool AgentPool, options *AgentPoolClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "AgentPoolClient.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, connectedClusterResourceURI, agentPoolName, agentPool, 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 *AgentPoolClient) createOrUpdateCreateRequest(ctx context.Context, connectedClusterResourceURI string, agentPoolName string, agentPool AgentPool, options *AgentPoolClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/{connectedClusterResourceUri}/providers/Microsoft.HybridContainerService/provisionedClusterInstances/default/agentPools/{agentPoolName}"
	urlPath = strings.ReplaceAll(urlPath, "{connectedClusterResourceUri}", connectedClusterResourceURI)
	if agentPoolName == "" {
		return nil, errors.New("parameter agentPoolName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{agentPoolName}", url.PathEscape(agentPoolName))
	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-01-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, agentPool); err != nil {
		return nil, err
	}
	return req, nil
}

// BeginDelete - Deletes the specified agent pool in the provisioned cluster
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-01-01
//   - connectedClusterResourceURI - The fully qualified Azure Resource Manager identifier of the connected cluster resource.
//   - agentPoolName - Parameter for the name of the agent pool in the provisioned cluster.
//   - options - AgentPoolClientBeginDeleteOptions contains the optional parameters for the AgentPoolClient.BeginDelete method.
func (client *AgentPoolClient) BeginDelete(ctx context.Context, connectedClusterResourceURI string, agentPoolName string, options *AgentPoolClientBeginDeleteOptions) (*runtime.Poller[AgentPoolClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, connectedClusterResourceURI, agentPoolName, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AgentPoolClientDeleteResponse]{
			FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AgentPoolClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Deletes the specified agent pool in the provisioned cluster
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-01-01
func (client *AgentPoolClient) deleteOperation(ctx context.Context, connectedClusterResourceURI string, agentPoolName string, options *AgentPoolClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "AgentPoolClient.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, connectedClusterResourceURI, agentPoolName, 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 *AgentPoolClient) deleteCreateRequest(ctx context.Context, connectedClusterResourceURI string, agentPoolName string, options *AgentPoolClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/{connectedClusterResourceUri}/providers/Microsoft.HybridContainerService/provisionedClusterInstances/default/agentPools/{agentPoolName}"
	urlPath = strings.ReplaceAll(urlPath, "{connectedClusterResourceUri}", connectedClusterResourceURI)
	if agentPoolName == "" {
		return nil, errors.New("parameter agentPoolName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{agentPoolName}", url.PathEscape(agentPoolName))
	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-01-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Gets the specified agent pool in the provisioned cluster
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2024-01-01
//   - connectedClusterResourceURI - The fully qualified Azure Resource Manager identifier of the connected cluster resource.
//   - agentPoolName - Parameter for the name of the agent pool in the provisioned cluster.
//   - options - AgentPoolClientGetOptions contains the optional parameters for the AgentPoolClient.Get method.
func (client *AgentPoolClient) Get(ctx context.Context, connectedClusterResourceURI string, agentPoolName string, options *AgentPoolClientGetOptions) (AgentPoolClientGetResponse, error) {
	var err error
	const operationName = "AgentPoolClient.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, connectedClusterResourceURI, agentPoolName, options)
	if err != nil {
		return AgentPoolClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return AgentPoolClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return AgentPoolClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *AgentPoolClient) getCreateRequest(ctx context.Context, connectedClusterResourceURI string, agentPoolName string, options *AgentPoolClientGetOptions) (*policy.Request, error) {
	urlPath := "/{connectedClusterResourceUri}/providers/Microsoft.HybridContainerService/provisionedClusterInstances/default/agentPools/{agentPoolName}"
	urlPath = strings.ReplaceAll(urlPath, "{connectedClusterResourceUri}", connectedClusterResourceURI)
	if agentPoolName == "" {
		return nil, errors.New("parameter agentPoolName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{agentPoolName}", url.PathEscape(agentPoolName))
	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-01-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// NewListByProvisionedClusterPager - Gets the list of agent pools in the specified provisioned cluster
//
// Generated from API version 2024-01-01
//   - connectedClusterResourceURI - The fully qualified Azure Resource Manager identifier of the connected cluster resource.
//   - options - AgentPoolClientListByProvisionedClusterOptions contains the optional parameters for the AgentPoolClient.NewListByProvisionedClusterPager
//     method.
func (client *AgentPoolClient) NewListByProvisionedClusterPager(connectedClusterResourceURI string, options *AgentPoolClientListByProvisionedClusterOptions) *runtime.Pager[AgentPoolClientListByProvisionedClusterResponse] {
	return runtime.NewPager(runtime.PagingHandler[AgentPoolClientListByProvisionedClusterResponse]{
		More: func(page AgentPoolClientListByProvisionedClusterResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *AgentPoolClientListByProvisionedClusterResponse) (AgentPoolClientListByProvisionedClusterResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AgentPoolClient.NewListByProvisionedClusterPager")
			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.listByProvisionedClusterCreateRequest(ctx, connectedClusterResourceURI, options)
			}, nil)
			if err != nil {
				return AgentPoolClientListByProvisionedClusterResponse{}, err
			}
			return client.listByProvisionedClusterHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByProvisionedClusterCreateRequest creates the ListByProvisionedCluster request.
func (client *AgentPoolClient) listByProvisionedClusterCreateRequest(ctx context.Context, connectedClusterResourceURI string, options *AgentPoolClientListByProvisionedClusterOptions) (*policy.Request, error) {
	urlPath := "/{connectedClusterResourceUri}/providers/Microsoft.HybridContainerService/provisionedClusterInstances/default/agentPools"
	urlPath = strings.ReplaceAll(urlPath, "{connectedClusterResourceUri}", connectedClusterResourceURI)
	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-01-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByProvisionedClusterHandleResponse handles the ListByProvisionedCluster response.
func (client *AgentPoolClient) listByProvisionedClusterHandleResponse(resp *http.Response) (AgentPoolClientListByProvisionedClusterResponse, error) {
	result := AgentPoolClientListByProvisionedClusterResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.AgentPoolListResult); err != nil {
		return AgentPoolClientListByProvisionedClusterResponse{}, err
	}
	return result, nil
}
