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

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

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

// NewApplicationResourcesClient creates a new instance of ApplicationResourcesClient 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 NewApplicationResourcesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ApplicationResourcesClient, error) {
	cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
	if err != nil {
		return nil, err
	}
	client := &ApplicationResourcesClient{
		subscriptionID: subscriptionID,
		internal:       cl,
	}
	return client, nil
}

// CreateOrUpdate - Create a ApplicationResource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-11-14-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - spaceName - The name of the space
//   - applicationName - The name of the Application
//   - resourceName - The name of the application resource.
//   - resource - Resource create parameters.
//   - options - ApplicationResourcesClientCreateOrUpdateOptions contains the optional parameters for the ApplicationResourcesClient.CreateOrUpdate
//     method.
func (client *ApplicationResourcesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, spaceName string, applicationName string, resourceName string, resource ApplicationResource, options *ApplicationResourcesClientCreateOrUpdateOptions) (ApplicationResourcesClientCreateOrUpdateResponse, error) {
	var err error
	const operationName = "ApplicationResourcesClient.CreateOrUpdate"
	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, resourceGroupName, spaceName, applicationName, resourceName, resource, options)
	if err != nil {
		return ApplicationResourcesClientCreateOrUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return ApplicationResourcesClientCreateOrUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return ApplicationResourcesClientCreateOrUpdateResponse{}, err
	}
	resp, err := client.createOrUpdateHandleResponse(httpResp)
	return resp, err
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *ApplicationResourcesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, spaceName string, applicationName string, resourceName string, resource ApplicationResource, options *ApplicationResourcesClientCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.IntegrationSpaces/spaces/{spaceName}/applications/{applicationName}/resources/{resourceName}"
	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 spaceName == "" {
		return nil, errors.New("parameter spaceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{spaceName}", url.PathEscape(spaceName))
	if applicationName == "" {
		return nil, errors.New("parameter applicationName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{applicationName}", url.PathEscape(applicationName))
	if resourceName == "" {
		return nil, errors.New("parameter resourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName))
	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", "2023-11-14-preview")
	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
}

// createOrUpdateHandleResponse handles the CreateOrUpdate response.
func (client *ApplicationResourcesClient) createOrUpdateHandleResponse(resp *http.Response) (ApplicationResourcesClientCreateOrUpdateResponse, error) {
	result := ApplicationResourcesClientCreateOrUpdateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationResource); err != nil {
		return ApplicationResourcesClientCreateOrUpdateResponse{}, err
	}
	return result, nil
}

// Delete - Delete a ApplicationResource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-11-14-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - spaceName - The name of the space
//   - applicationName - The name of the Application
//   - resourceName - The name of the application resource.
//   - options - ApplicationResourcesClientDeleteOptions contains the optional parameters for the ApplicationResourcesClient.Delete
//     method.
func (client *ApplicationResourcesClient) Delete(ctx context.Context, resourceGroupName string, spaceName string, applicationName string, resourceName string, options *ApplicationResourcesClientDeleteOptions) (ApplicationResourcesClientDeleteResponse, error) {
	var err error
	const operationName = "ApplicationResourcesClient.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, spaceName, applicationName, resourceName, options)
	if err != nil {
		return ApplicationResourcesClientDeleteResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return ApplicationResourcesClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return ApplicationResourcesClientDeleteResponse{}, err
	}
	return ApplicationResourcesClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *ApplicationResourcesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, spaceName string, applicationName string, resourceName string, options *ApplicationResourcesClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.IntegrationSpaces/spaces/{spaceName}/applications/{applicationName}/resources/{resourceName}"
	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 spaceName == "" {
		return nil, errors.New("parameter spaceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{spaceName}", url.PathEscape(spaceName))
	if applicationName == "" {
		return nil, errors.New("parameter applicationName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{applicationName}", url.PathEscape(applicationName))
	if resourceName == "" {
		return nil, errors.New("parameter resourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName))
	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", "2023-11-14-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Get a ApplicationResource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-11-14-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - spaceName - The name of the space
//   - applicationName - The name of the Application
//   - resourceName - The name of the application resource.
//   - options - ApplicationResourcesClientGetOptions contains the optional parameters for the ApplicationResourcesClient.Get
//     method.
func (client *ApplicationResourcesClient) Get(ctx context.Context, resourceGroupName string, spaceName string, applicationName string, resourceName string, options *ApplicationResourcesClientGetOptions) (ApplicationResourcesClientGetResponse, error) {
	var err error
	const operationName = "ApplicationResourcesClient.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, spaceName, applicationName, resourceName, options)
	if err != nil {
		return ApplicationResourcesClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return ApplicationResourcesClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return ApplicationResourcesClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *ApplicationResourcesClient) getCreateRequest(ctx context.Context, resourceGroupName string, spaceName string, applicationName string, resourceName string, options *ApplicationResourcesClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.IntegrationSpaces/spaces/{spaceName}/applications/{applicationName}/resources/{resourceName}"
	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 spaceName == "" {
		return nil, errors.New("parameter spaceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{spaceName}", url.PathEscape(spaceName))
	if applicationName == "" {
		return nil, errors.New("parameter applicationName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{applicationName}", url.PathEscape(applicationName))
	if resourceName == "" {
		return nil, errors.New("parameter resourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName))
	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", "2023-11-14-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// NewListByApplicationPager - List ApplicationResource resources by Application
//
// Generated from API version 2023-11-14-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - spaceName - The name of the space
//   - applicationName - The name of the Application
//   - options - ApplicationResourcesClientListByApplicationOptions contains the optional parameters for the ApplicationResourcesClient.NewListByApplicationPager
//     method.
func (client *ApplicationResourcesClient) NewListByApplicationPager(resourceGroupName string, spaceName string, applicationName string, options *ApplicationResourcesClientListByApplicationOptions) *runtime.Pager[ApplicationResourcesClientListByApplicationResponse] {
	return runtime.NewPager(runtime.PagingHandler[ApplicationResourcesClientListByApplicationResponse]{
		More: func(page ApplicationResourcesClientListByApplicationResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *ApplicationResourcesClientListByApplicationResponse) (ApplicationResourcesClientListByApplicationResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ApplicationResourcesClient.NewListByApplicationPager")
			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.listByApplicationCreateRequest(ctx, resourceGroupName, spaceName, applicationName, options)
			}, nil)
			if err != nil {
				return ApplicationResourcesClientListByApplicationResponse{}, err
			}
			return client.listByApplicationHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByApplicationCreateRequest creates the ListByApplication request.
func (client *ApplicationResourcesClient) listByApplicationCreateRequest(ctx context.Context, resourceGroupName string, spaceName string, applicationName string, options *ApplicationResourcesClientListByApplicationOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.IntegrationSpaces/spaces/{spaceName}/applications/{applicationName}/resources"
	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 spaceName == "" {
		return nil, errors.New("parameter spaceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{spaceName}", url.PathEscape(spaceName))
	if applicationName == "" {
		return nil, errors.New("parameter applicationName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{applicationName}", url.PathEscape(applicationName))
	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", "2023-11-14-preview")
	if options != nil && options.Top != nil {
		reqQP.Set("top", strconv.FormatInt(int64(*options.Top), 10))
	}
	if options != nil && options.Skip != nil {
		reqQP.Set("skip", strconv.FormatInt(int64(*options.Skip), 10))
	}
	if options != nil && options.Maxpagesize != nil {
		reqQP.Set("maxpagesize", strconv.FormatInt(int64(*options.Maxpagesize), 10))
	}
	if options != nil && options.Filter != nil {
		reqQP.Set("filter", *options.Filter)
	}
	if options != nil && options.Select != nil {
		for _, qv := range options.Select {
			reqQP.Add("select", qv)
		}
	}
	if options != nil && options.Expand != nil {
		for _, qv := range options.Expand {
			reqQP.Add("expand", qv)
		}
	}
	if options != nil && options.Orderby != nil {
		for _, qv := range options.Orderby {
			reqQP.Add("orderby", qv)
		}
	}
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByApplicationHandleResponse handles the ListByApplication response.
func (client *ApplicationResourcesClient) listByApplicationHandleResponse(resp *http.Response) (ApplicationResourcesClientListByApplicationResponse, error) {
	result := ApplicationResourcesClientListByApplicationResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationResourceListResult); err != nil {
		return ApplicationResourcesClientListByApplicationResponse{}, err
	}
	return result, nil
}

// Patch - Update a ApplicationResource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-11-14-preview
//   - resourceGroupName - The name of the resource group. The name is case insensitive.
//   - spaceName - The name of the space
//   - applicationName - The name of the Application
//   - resourceName - The name of the application resource.
//   - properties - The resource properties to be updated.
//   - options - ApplicationResourcesClientPatchOptions contains the optional parameters for the ApplicationResourcesClient.Patch
//     method.
func (client *ApplicationResourcesClient) Patch(ctx context.Context, resourceGroupName string, spaceName string, applicationName string, resourceName string, properties ApplicationResourceUpdate, options *ApplicationResourcesClientPatchOptions) (ApplicationResourcesClientPatchResponse, error) {
	var err error
	const operationName = "ApplicationResourcesClient.Patch"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.patchCreateRequest(ctx, resourceGroupName, spaceName, applicationName, resourceName, properties, options)
	if err != nil {
		return ApplicationResourcesClientPatchResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return ApplicationResourcesClientPatchResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return ApplicationResourcesClientPatchResponse{}, err
	}
	resp, err := client.patchHandleResponse(httpResp)
	return resp, err
}

// patchCreateRequest creates the Patch request.
func (client *ApplicationResourcesClient) patchCreateRequest(ctx context.Context, resourceGroupName string, spaceName string, applicationName string, resourceName string, properties ApplicationResourceUpdate, options *ApplicationResourcesClientPatchOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.IntegrationSpaces/spaces/{spaceName}/applications/{applicationName}/resources/{resourceName}"
	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 spaceName == "" {
		return nil, errors.New("parameter spaceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{spaceName}", url.PathEscape(spaceName))
	if applicationName == "" {
		return nil, errors.New("parameter applicationName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{applicationName}", url.PathEscape(applicationName))
	if resourceName == "" {
		return nil, errors.New("parameter resourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName))
	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", "2023-11-14-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, properties); err != nil {
		return nil, err
	}
	return req, nil
}

// patchHandleResponse handles the Patch response.
func (client *ApplicationResourcesClient) patchHandleResponse(resp *http.Response) (ApplicationResourcesClientPatchResponse, error) {
	result := ApplicationResourcesClientPatchResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.ApplicationResource); err != nil {
		return ApplicationResourcesClientPatchResponse{}, err
	}
	return result, nil
}
