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

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

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

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

// BeginCreateOrUpdate - Creates or updates the data store/repository in the data manager.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2019-06-01
//   - dataStoreName - The data store/repository name to be created or updated.
//   - resourceGroupName - The Resource Group Name
//   - dataManagerName - The name of the DataManager Resource within the specified resource group. DataManager names must be between
//     3 and 24 characters in length and use any alphanumeric and underscore only
//   - dataStore - The data store/repository object to be created or updated.
//   - options - DataStoresClientBeginCreateOrUpdateOptions contains the optional parameters for the DataStoresClient.BeginCreateOrUpdate
//     method.
func (client *DataStoresClient) BeginCreateOrUpdate(ctx context.Context, dataStoreName string, resourceGroupName string, dataManagerName string, dataStore DataStore, options *DataStoresClientBeginCreateOrUpdateOptions) (*runtime.Poller[DataStoresClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, dataStoreName, resourceGroupName, dataManagerName, dataStore, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DataStoresClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DataStoresClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Creates or updates the data store/repository in the data manager.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2019-06-01
func (client *DataStoresClient) createOrUpdate(ctx context.Context, dataStoreName string, resourceGroupName string, dataManagerName string, dataStore DataStore, options *DataStoresClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "DataStoresClient.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, dataStoreName, resourceGroupName, dataManagerName, dataStore, 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
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *DataStoresClient) createOrUpdateCreateRequest(ctx context.Context, dataStoreName string, resourceGroupName string, dataManagerName string, dataStore DataStore, options *DataStoresClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridData/dataManagers/{dataManagerName}/dataStores/{dataStoreName}"
	if dataStoreName == "" {
		return nil, errors.New("parameter dataStoreName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{dataStoreName}", url.PathEscape(dataStoreName))
	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 dataManagerName == "" {
		return nil, errors.New("parameter dataManagerName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{dataManagerName}", url.PathEscape(dataManagerName))
	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", "2019-06-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, dataStore); err != nil {
		return nil, err
	}
	return req, nil
}

// BeginDelete - This method deletes the given data store/repository.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2019-06-01
//   - dataStoreName - The data store/repository name to be deleted.
//   - resourceGroupName - The Resource Group Name
//   - dataManagerName - The name of the DataManager Resource within the specified resource group. DataManager names must be between
//     3 and 24 characters in length and use any alphanumeric and underscore only
//   - options - DataStoresClientBeginDeleteOptions contains the optional parameters for the DataStoresClient.BeginDelete method.
func (client *DataStoresClient) BeginDelete(ctx context.Context, dataStoreName string, resourceGroupName string, dataManagerName string, options *DataStoresClientBeginDeleteOptions) (*runtime.Poller[DataStoresClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, dataStoreName, resourceGroupName, dataManagerName, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DataStoresClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DataStoresClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - This method deletes the given data store/repository.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2019-06-01
func (client *DataStoresClient) deleteOperation(ctx context.Context, dataStoreName string, resourceGroupName string, dataManagerName string, options *DataStoresClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "DataStoresClient.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, dataStoreName, resourceGroupName, dataManagerName, 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 *DataStoresClient) deleteCreateRequest(ctx context.Context, dataStoreName string, resourceGroupName string, dataManagerName string, options *DataStoresClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridData/dataManagers/{dataManagerName}/dataStores/{dataStoreName}"
	if dataStoreName == "" {
		return nil, errors.New("parameter dataStoreName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{dataStoreName}", url.PathEscape(dataStoreName))
	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 dataManagerName == "" {
		return nil, errors.New("parameter dataManagerName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{dataManagerName}", url.PathEscape(dataManagerName))
	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", "2019-06-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	return req, nil
}

// Get - This method gets the data store/repository by name.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2019-06-01
//   - dataStoreName - The data store/repository name queried.
//   - resourceGroupName - The Resource Group Name
//   - dataManagerName - The name of the DataManager Resource within the specified resource group. DataManager names must be between
//     3 and 24 characters in length and use any alphanumeric and underscore only
//   - options - DataStoresClientGetOptions contains the optional parameters for the DataStoresClient.Get method.
func (client *DataStoresClient) Get(ctx context.Context, dataStoreName string, resourceGroupName string, dataManagerName string, options *DataStoresClientGetOptions) (DataStoresClientGetResponse, error) {
	var err error
	const operationName = "DataStoresClient.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, dataStoreName, resourceGroupName, dataManagerName, options)
	if err != nil {
		return DataStoresClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return DataStoresClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return DataStoresClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *DataStoresClient) getCreateRequest(ctx context.Context, dataStoreName string, resourceGroupName string, dataManagerName string, options *DataStoresClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridData/dataManagers/{dataManagerName}/dataStores/{dataStoreName}"
	if dataStoreName == "" {
		return nil, errors.New("parameter dataStoreName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{dataStoreName}", url.PathEscape(dataStoreName))
	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 dataManagerName == "" {
		return nil, errors.New("parameter dataManagerName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{dataManagerName}", url.PathEscape(dataManagerName))
	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", "2019-06-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// NewListByDataManagerPager - Gets all the data stores/repositories in the given resource.
//
// Generated from API version 2019-06-01
//   - resourceGroupName - The Resource Group Name
//   - dataManagerName - The name of the DataManager Resource within the specified resource group. DataManager names must be between
//     3 and 24 characters in length and use any alphanumeric and underscore only
//   - options - DataStoresClientListByDataManagerOptions contains the optional parameters for the DataStoresClient.NewListByDataManagerPager
//     method.
func (client *DataStoresClient) NewListByDataManagerPager(resourceGroupName string, dataManagerName string, options *DataStoresClientListByDataManagerOptions) *runtime.Pager[DataStoresClientListByDataManagerResponse] {
	return runtime.NewPager(runtime.PagingHandler[DataStoresClientListByDataManagerResponse]{
		More: func(page DataStoresClientListByDataManagerResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *DataStoresClientListByDataManagerResponse) (DataStoresClientListByDataManagerResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DataStoresClient.NewListByDataManagerPager")
			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.listByDataManagerCreateRequest(ctx, resourceGroupName, dataManagerName, options)
			}, nil)
			if err != nil {
				return DataStoresClientListByDataManagerResponse{}, err
			}
			return client.listByDataManagerHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByDataManagerCreateRequest creates the ListByDataManager request.
func (client *DataStoresClient) listByDataManagerCreateRequest(ctx context.Context, resourceGroupName string, dataManagerName string, options *DataStoresClientListByDataManagerOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridData/dataManagers/{dataManagerName}/dataStores"
	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 dataManagerName == "" {
		return nil, errors.New("parameter dataManagerName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{dataManagerName}", url.PathEscape(dataManagerName))
	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", "2019-06-01")
	if options != nil && options.Filter != nil {
		reqQP.Set("$filter", *options.Filter)
	}
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByDataManagerHandleResponse handles the ListByDataManager response.
func (client *DataStoresClient) listByDataManagerHandleResponse(resp *http.Response) (DataStoresClientListByDataManagerResponse, error) {
	result := DataStoresClientListByDataManagerResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.DataStoreList); err != nil {
		return DataStoresClientListByDataManagerResponse{}, err
	}
	return result, nil
}
