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

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

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

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

// Create - Install extension.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2021-09-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - farmBeatsResourceName - FarmBeats resource name.
//   - extensionID - Id of extension resource.
//   - options - ExtensionsClientCreateOptions contains the optional parameters for the ExtensionsClient.Create method.
func (client *ExtensionsClient) Create(ctx context.Context, resourceGroupName string, farmBeatsResourceName string, extensionID string, options *ExtensionsClientCreateOptions) (ExtensionsClientCreateResponse, error) {
	var err error
	const operationName = "ExtensionsClient.Create"
	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, farmBeatsResourceName, extensionID, options)
	if err != nil {
		return ExtensionsClientCreateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return ExtensionsClientCreateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return ExtensionsClientCreateResponse{}, err
	}
	resp, err := client.createHandleResponse(httpResp)
	return resp, err
}

// createCreateRequest creates the Create request.
func (client *ExtensionsClient) createCreateRequest(ctx context.Context, resourceGroupName string, farmBeatsResourceName string, extensionID string, options *ExtensionsClientCreateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgFoodPlatform/farmBeats/{farmBeatsResourceName}/extensions/{extensionId}"
	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 farmBeatsResourceName == "" {
		return nil, errors.New("parameter farmBeatsResourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{farmBeatsResourceName}", url.PathEscape(farmBeatsResourceName))
	if extensionID == "" {
		return nil, errors.New("parameter extensionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{extensionId}", url.PathEscape(extensionID))
	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", "2021-09-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// createHandleResponse handles the Create response.
func (client *ExtensionsClient) createHandleResponse(resp *http.Response) (ExtensionsClientCreateResponse, error) {
	result := ExtensionsClientCreateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Extension); err != nil {
		return ExtensionsClientCreateResponse{}, err
	}
	return result, nil
}

// Delete - Uninstall extension.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2021-09-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - farmBeatsResourceName - FarmBeats resource name.
//   - extensionID - Id of extension resource.
//   - options - ExtensionsClientDeleteOptions contains the optional parameters for the ExtensionsClient.Delete method.
func (client *ExtensionsClient) Delete(ctx context.Context, resourceGroupName string, farmBeatsResourceName string, extensionID string, options *ExtensionsClientDeleteOptions) (ExtensionsClientDeleteResponse, error) {
	var err error
	const operationName = "ExtensionsClient.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, farmBeatsResourceName, extensionID, options)
	if err != nil {
		return ExtensionsClientDeleteResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return ExtensionsClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return ExtensionsClientDeleteResponse{}, err
	}
	return ExtensionsClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *ExtensionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, farmBeatsResourceName string, extensionID string, options *ExtensionsClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgFoodPlatform/farmBeats/{farmBeatsResourceName}/extensions/{extensionId}"
	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 farmBeatsResourceName == "" {
		return nil, errors.New("parameter farmBeatsResourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{farmBeatsResourceName}", url.PathEscape(farmBeatsResourceName))
	if extensionID == "" {
		return nil, errors.New("parameter extensionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{extensionId}", url.PathEscape(extensionID))
	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", "2021-09-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Get installed extension details by extension id.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2021-09-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - farmBeatsResourceName - FarmBeats resource name.
//   - extensionID - Id of extension resource.
//   - options - ExtensionsClientGetOptions contains the optional parameters for the ExtensionsClient.Get method.
func (client *ExtensionsClient) Get(ctx context.Context, resourceGroupName string, farmBeatsResourceName string, extensionID string, options *ExtensionsClientGetOptions) (ExtensionsClientGetResponse, error) {
	var err error
	const operationName = "ExtensionsClient.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, farmBeatsResourceName, extensionID, options)
	if err != nil {
		return ExtensionsClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return ExtensionsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return ExtensionsClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *ExtensionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, farmBeatsResourceName string, extensionID string, options *ExtensionsClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgFoodPlatform/farmBeats/{farmBeatsResourceName}/extensions/{extensionId}"
	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 farmBeatsResourceName == "" {
		return nil, errors.New("parameter farmBeatsResourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{farmBeatsResourceName}", url.PathEscape(farmBeatsResourceName))
	if extensionID == "" {
		return nil, errors.New("parameter extensionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{extensionId}", url.PathEscape(extensionID))
	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", "2021-09-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 *ExtensionsClient) getHandleResponse(resp *http.Response) (ExtensionsClientGetResponse, error) {
	result := ExtensionsClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Extension); err != nil {
		return ExtensionsClientGetResponse{}, err
	}
	return result, nil
}

// NewListByFarmBeatsPager - Get installed extensions details.
//
// Generated from API version 2021-09-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - farmBeatsResourceName - FarmBeats resource name.
//   - options - ExtensionsClientListByFarmBeatsOptions contains the optional parameters for the ExtensionsClient.NewListByFarmBeatsPager
//     method.
func (client *ExtensionsClient) NewListByFarmBeatsPager(resourceGroupName string, farmBeatsResourceName string, options *ExtensionsClientListByFarmBeatsOptions) *runtime.Pager[ExtensionsClientListByFarmBeatsResponse] {
	return runtime.NewPager(runtime.PagingHandler[ExtensionsClientListByFarmBeatsResponse]{
		More: func(page ExtensionsClientListByFarmBeatsResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *ExtensionsClientListByFarmBeatsResponse) (ExtensionsClientListByFarmBeatsResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExtensionsClient.NewListByFarmBeatsPager")
			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.listByFarmBeatsCreateRequest(ctx, resourceGroupName, farmBeatsResourceName, options)
			}, nil)
			if err != nil {
				return ExtensionsClientListByFarmBeatsResponse{}, err
			}
			return client.listByFarmBeatsHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByFarmBeatsCreateRequest creates the ListByFarmBeats request.
func (client *ExtensionsClient) listByFarmBeatsCreateRequest(ctx context.Context, resourceGroupName string, farmBeatsResourceName string, options *ExtensionsClientListByFarmBeatsOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgFoodPlatform/farmBeats/{farmBeatsResourceName}/extensions"
	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 farmBeatsResourceName == "" {
		return nil, errors.New("parameter farmBeatsResourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{farmBeatsResourceName}", url.PathEscape(farmBeatsResourceName))
	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", "2021-09-01-preview")
	if options != nil && options.ExtensionIDs != nil {
		for _, qv := range options.ExtensionIDs {
			reqQP.Add("extensionIds", qv)
		}
	}
	if options != nil && options.ExtensionCategories != nil {
		for _, qv := range options.ExtensionCategories {
			reqQP.Add("extensionCategories", qv)
		}
	}
	if options != nil && options.MaxPageSize != nil {
		reqQP.Set("$maxPageSize", strconv.FormatInt(int64(*options.MaxPageSize), 10))
	}
	if options != nil && options.SkipToken != nil {
		reqQP.Set("$skipToken", *options.SkipToken)
	}
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByFarmBeatsHandleResponse handles the ListByFarmBeats response.
func (client *ExtensionsClient) listByFarmBeatsHandleResponse(resp *http.Response) (ExtensionsClientListByFarmBeatsResponse, error) {
	result := ExtensionsClientListByFarmBeatsResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ExtensionListResponse); err != nil {
		return ExtensionsClientListByFarmBeatsResponse{}, err
	}
	return result, nil
}

// Update - Upgrade to latest extension.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2021-09-01-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - farmBeatsResourceName - FarmBeats resource name.
//   - extensionID - Id of extension resource.
//   - options - ExtensionsClientUpdateOptions contains the optional parameters for the ExtensionsClient.Update method.
func (client *ExtensionsClient) Update(ctx context.Context, resourceGroupName string, farmBeatsResourceName string, extensionID string, options *ExtensionsClientUpdateOptions) (ExtensionsClientUpdateResponse, error) {
	var err error
	const operationName = "ExtensionsClient.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, farmBeatsResourceName, extensionID, options)
	if err != nil {
		return ExtensionsClientUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return ExtensionsClientUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return ExtensionsClientUpdateResponse{}, err
	}
	resp, err := client.updateHandleResponse(httpResp)
	return resp, err
}

// updateCreateRequest creates the Update request.
func (client *ExtensionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, farmBeatsResourceName string, extensionID string, options *ExtensionsClientUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AgFoodPlatform/farmBeats/{farmBeatsResourceName}/extensions/{extensionId}"
	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 farmBeatsResourceName == "" {
		return nil, errors.New("parameter farmBeatsResourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{farmBeatsResourceName}", url.PathEscape(farmBeatsResourceName))
	if extensionID == "" {
		return nil, errors.New("parameter extensionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{extensionId}", url.PathEscape(extensionID))
	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", "2021-09-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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