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

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

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

// CreateOrUpdate - Create a Space
// 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
//   - resource - Resource create parameters.
//   - options - SpacesClientCreateOrUpdateOptions contains the optional parameters for the SpacesClient.CreateOrUpdate method.
func (client *SpacesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, spaceName string, resource Space, options *SpacesClientCreateOrUpdateOptions) (SpacesClientCreateOrUpdateResponse, error) {
	var err error
	const operationName = "SpacesClient.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, resource, options)
	if err != nil {
		return SpacesClientCreateOrUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return SpacesClientCreateOrUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return SpacesClientCreateOrUpdateResponse{}, err
	}
	resp, err := client.createOrUpdateHandleResponse(httpResp)
	return resp, err
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *SpacesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, spaceName string, resource Space, options *SpacesClientCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.IntegrationSpaces/spaces/{spaceName}"
	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))
	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 *SpacesClient) createOrUpdateHandleResponse(resp *http.Response) (SpacesClientCreateOrUpdateResponse, error) {
	result := SpacesClientCreateOrUpdateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Space); err != nil {
		return SpacesClientCreateOrUpdateResponse{}, err
	}
	return result, nil
}

// Delete - Delete a Space
// 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
//   - options - SpacesClientDeleteOptions contains the optional parameters for the SpacesClient.Delete method.
func (client *SpacesClient) Delete(ctx context.Context, resourceGroupName string, spaceName string, options *SpacesClientDeleteOptions) (SpacesClientDeleteResponse, error) {
	var err error
	const operationName = "SpacesClient.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, options)
	if err != nil {
		return SpacesClientDeleteResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return SpacesClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return SpacesClientDeleteResponse{}, err
	}
	return SpacesClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *SpacesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, spaceName string, options *SpacesClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.IntegrationSpaces/spaces/{spaceName}"
	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))
	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 Space
// 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
//   - options - SpacesClientGetOptions contains the optional parameters for the SpacesClient.Get method.
func (client *SpacesClient) Get(ctx context.Context, resourceGroupName string, spaceName string, options *SpacesClientGetOptions) (SpacesClientGetResponse, error) {
	var err error
	const operationName = "SpacesClient.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, options)
	if err != nil {
		return SpacesClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return SpacesClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return SpacesClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *SpacesClient) getCreateRequest(ctx context.Context, resourceGroupName string, spaceName string, options *SpacesClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.IntegrationSpaces/spaces/{spaceName}"
	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))
	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 *SpacesClient) getHandleResponse(resp *http.Response) (SpacesClientGetResponse, error) {
	result := SpacesClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Space); err != nil {
		return SpacesClientGetResponse{}, err
	}
	return result, nil
}

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

// listByResourceGroupCreateRequest creates the ListByResourceGroup request.
func (client *SpacesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *SpacesClientListByResourceGroupOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.IntegrationSpaces/spaces"
	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", "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
}

// listByResourceGroupHandleResponse handles the ListByResourceGroup response.
func (client *SpacesClient) listByResourceGroupHandleResponse(resp *http.Response) (SpacesClientListByResourceGroupResponse, error) {
	result := SpacesClientListByResourceGroupResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.SpaceListResult); err != nil {
		return SpacesClientListByResourceGroupResponse{}, err
	}
	return result, nil
}

// NewListBySubscriptionPager - List Space resources by subscription ID
//
// Generated from API version 2023-11-14-preview
//   - options - SpacesClientListBySubscriptionOptions contains the optional parameters for the SpacesClient.NewListBySubscriptionPager
//     method.
func (client *SpacesClient) NewListBySubscriptionPager(options *SpacesClientListBySubscriptionOptions) *runtime.Pager[SpacesClientListBySubscriptionResponse] {
	return runtime.NewPager(runtime.PagingHandler[SpacesClientListBySubscriptionResponse]{
		More: func(page SpacesClientListBySubscriptionResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *SpacesClientListBySubscriptionResponse) (SpacesClientListBySubscriptionResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SpacesClient.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 SpacesClientListBySubscriptionResponse{}, err
			}
			return client.listBySubscriptionHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listBySubscriptionCreateRequest creates the ListBySubscription request.
func (client *SpacesClient) listBySubscriptionCreateRequest(ctx context.Context, options *SpacesClientListBySubscriptionOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.IntegrationSpaces/spaces"
	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", "2023-11-14-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// Patch - Update a Space
// 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
//   - properties - The resource properties to be updated.
//   - options - SpacesClientPatchOptions contains the optional parameters for the SpacesClient.Patch method.
func (client *SpacesClient) Patch(ctx context.Context, resourceGroupName string, spaceName string, properties SpaceUpdate, options *SpacesClientPatchOptions) (SpacesClientPatchResponse, error) {
	var err error
	const operationName = "SpacesClient.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, properties, options)
	if err != nil {
		return SpacesClientPatchResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return SpacesClientPatchResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return SpacesClientPatchResponse{}, err
	}
	resp, err := client.patchHandleResponse(httpResp)
	return resp, err
}

// patchCreateRequest creates the Patch request.
func (client *SpacesClient) patchCreateRequest(ctx context.Context, resourceGroupName string, spaceName string, properties SpaceUpdate, options *SpacesClientPatchOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.IntegrationSpaces/spaces/{spaceName}"
	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))
	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 *SpacesClient) patchHandleResponse(resp *http.Response) (SpacesClientPatchResponse, error) {
	result := SpacesClientPatchResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Space); err != nil {
		return SpacesClientPatchResponse{}, err
	}
	return result, nil
}
