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

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

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

// NewLinksClient creates a new instance of LinksClient with the specified values.
//   - subscriptionID - Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID
//     forms part of the URI for every service call.
//   - credential - used to authorize requests. Usually a credential from azidentity.
//   - options - pass nil to accept the default values.
func NewLinksClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LinksClient, error) {
	cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
	if err != nil {
		return nil, err
	}
	client := &LinksClient{
		subscriptionID: subscriptionID,
		internal:       cl,
	}
	return client, nil
}

// BeginCreateOrUpdate - Creates a link or updates an existing link in the hub.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2017-04-26
//   - resourceGroupName - The name of the resource group.
//   - hubName - The name of the hub.
//   - linkName - The name of the link.
//   - parameters - Parameters supplied to the CreateOrUpdate Link operation.
//   - options - LinksClientBeginCreateOrUpdateOptions contains the optional parameters for the LinksClient.BeginCreateOrUpdate
//     method.
func (client *LinksClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, hubName string, linkName string, parameters LinkResourceFormat, options *LinksClientBeginCreateOrUpdateOptions) (*runtime.Poller[LinksClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, resourceGroupName, hubName, linkName, parameters, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LinksClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LinksClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Creates a link or updates an existing link in the hub.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2017-04-26
func (client *LinksClient) createOrUpdate(ctx context.Context, resourceGroupName string, hubName string, linkName string, parameters LinkResourceFormat, options *LinksClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "LinksClient.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, resourceGroupName, hubName, linkName, parameters, 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 *LinksClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, hubName string, linkName string, parameters LinkResourceFormat, options *LinksClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/links/{linkName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if hubName == "" {
		return nil, errors.New("parameter hubName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{hubName}", url.PathEscape(hubName))
	if linkName == "" {
		return nil, errors.New("parameter linkName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{linkName}", url.PathEscape(linkName))
	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.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2017-04-26")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, parameters); err != nil {
		return nil, err
	}
	return req, nil
}

// Delete - Deletes a link in the hub.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2017-04-26
//   - resourceGroupName - The name of the resource group.
//   - hubName - The name of the hub.
//   - linkName - The name of the link.
//   - options - LinksClientDeleteOptions contains the optional parameters for the LinksClient.Delete method.
func (client *LinksClient) Delete(ctx context.Context, resourceGroupName string, hubName string, linkName string, options *LinksClientDeleteOptions) (LinksClientDeleteResponse, error) {
	var err error
	const operationName = "LinksClient.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, hubName, linkName, options)
	if err != nil {
		return LinksClientDeleteResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return LinksClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) {
		err = runtime.NewResponseError(httpResp)
		return LinksClientDeleteResponse{}, err
	}
	return LinksClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *LinksClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, hubName string, linkName string, options *LinksClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/links/{linkName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if hubName == "" {
		return nil, errors.New("parameter hubName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{hubName}", url.PathEscape(hubName))
	if linkName == "" {
		return nil, errors.New("parameter linkName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{linkName}", url.PathEscape(linkName))
	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.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2017-04-26")
	req.Raw().URL.RawQuery = reqQP.Encode()
	return req, nil
}

// Get - Gets a link in the hub.
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2017-04-26
//   - resourceGroupName - The name of the resource group.
//   - hubName - The name of the hub.
//   - linkName - The name of the link.
//   - options - LinksClientGetOptions contains the optional parameters for the LinksClient.Get method.
func (client *LinksClient) Get(ctx context.Context, resourceGroupName string, hubName string, linkName string, options *LinksClientGetOptions) (LinksClientGetResponse, error) {
	var err error
	const operationName = "LinksClient.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, hubName, linkName, options)
	if err != nil {
		return LinksClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return LinksClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return LinksClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *LinksClient) getCreateRequest(ctx context.Context, resourceGroupName string, hubName string, linkName string, options *LinksClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/links/{linkName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if hubName == "" {
		return nil, errors.New("parameter hubName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{hubName}", url.PathEscape(hubName))
	if linkName == "" {
		return nil, errors.New("parameter linkName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{linkName}", url.PathEscape(linkName))
	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", "2017-04-26")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// NewListByHubPager - Gets all the links in the specified hub.
//
// Generated from API version 2017-04-26
//   - resourceGroupName - The name of the resource group.
//   - hubName - The name of the hub.
//   - options - LinksClientListByHubOptions contains the optional parameters for the LinksClient.NewListByHubPager method.
func (client *LinksClient) NewListByHubPager(resourceGroupName string, hubName string, options *LinksClientListByHubOptions) *runtime.Pager[LinksClientListByHubResponse] {
	return runtime.NewPager(runtime.PagingHandler[LinksClientListByHubResponse]{
		More: func(page LinksClientListByHubResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *LinksClientListByHubResponse) (LinksClientListByHubResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LinksClient.NewListByHubPager")
			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.listByHubCreateRequest(ctx, resourceGroupName, hubName, options)
			}, nil)
			if err != nil {
				return LinksClientListByHubResponse{}, err
			}
			return client.listByHubHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listByHubCreateRequest creates the ListByHub request.
func (client *LinksClient) listByHubCreateRequest(ctx context.Context, resourceGroupName string, hubName string, options *LinksClientListByHubOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/links"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if hubName == "" {
		return nil, errors.New("parameter hubName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{hubName}", url.PathEscape(hubName))
	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", "2017-04-26")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByHubHandleResponse handles the ListByHub response.
func (client *LinksClient) listByHubHandleResponse(resp *http.Response) (LinksClientListByHubResponse, error) {
	result := LinksClientListByHubResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.LinkListResult); err != nil {
		return LinksClientListByHubResponse{}, err
	}
	return result, nil
}
