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

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

// PreRulesClient contains the methods for the PreRules group.
// Don't use this type directly, use NewPreRulesClient() instead.
type PreRulesClient struct {
	internal *arm.Client
}

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

// BeginCreateOrUpdate - Create a PreRulesResource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-09-01
//   - globalRulestackName - GlobalRulestack resource name
//   - priority - Pre Rule priority
//   - resource - Resource create parameters.
//   - options - PreRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the PreRulesClient.BeginCreateOrUpdate
//     method.
func (client *PreRulesClient) BeginCreateOrUpdate(ctx context.Context, globalRulestackName string, priority string, resource PreRulesResource, options *PreRulesClientBeginCreateOrUpdateOptions) (*runtime.Poller[PreRulesClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, globalRulestackName, priority, resource, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PreRulesClientCreateOrUpdateResponse]{
			FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PreRulesClientCreateOrUpdateResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// CreateOrUpdate - Create a PreRulesResource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-09-01
func (client *PreRulesClient) createOrUpdate(ctx context.Context, globalRulestackName string, priority string, resource PreRulesResource, options *PreRulesClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	var err error
	const operationName = "PreRulesClient.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, globalRulestackName, priority, resource, 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.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *PreRulesClient) createOrUpdateCreateRequest(ctx context.Context, globalRulestackName string, priority string, resource PreRulesResource, options *PreRulesClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/providers/PaloAltoNetworks.Cloudngfw/globalRulestacks/{globalRulestackName}/preRules/{priority}"
	if globalRulestackName == "" {
		return nil, errors.New("parameter globalRulestackName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{globalRulestackName}", url.PathEscape(globalRulestackName))
	if priority == "" {
		return nil, errors.New("parameter priority cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{priority}", url.PathEscape(priority))
	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-09-01")
	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
}

// BeginDelete - Delete a PreRulesResource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-09-01
//   - globalRulestackName - GlobalRulestack resource name
//   - priority - Pre Rule priority
//   - options - PreRulesClientBeginDeleteOptions contains the optional parameters for the PreRulesClient.BeginDelete method.
func (client *PreRulesClient) BeginDelete(ctx context.Context, globalRulestackName string, priority string, options *PreRulesClientBeginDeleteOptions) (*runtime.Poller[PreRulesClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, globalRulestackName, priority, options)
		if err != nil {
			return nil, err
		}
		poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PreRulesClientDeleteResponse]{
			FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
			Tracer:        client.internal.Tracer(),
		})
		return poller, err
	} else {
		return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PreRulesClientDeleteResponse]{
			Tracer: client.internal.Tracer(),
		})
	}
}

// Delete - Delete a PreRulesResource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-09-01
func (client *PreRulesClient) deleteOperation(ctx context.Context, globalRulestackName string, priority string, options *PreRulesClientBeginDeleteOptions) (*http.Response, error) {
	var err error
	const operationName = "PreRulesClient.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, globalRulestackName, priority, 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, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return nil, err
	}
	return httpResp, nil
}

// deleteCreateRequest creates the Delete request.
func (client *PreRulesClient) deleteCreateRequest(ctx context.Context, globalRulestackName string, priority string, options *PreRulesClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/providers/PaloAltoNetworks.Cloudngfw/globalRulestacks/{globalRulestackName}/preRules/{priority}"
	if globalRulestackName == "" {
		return nil, errors.New("parameter globalRulestackName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{globalRulestackName}", url.PathEscape(globalRulestackName))
	if priority == "" {
		return nil, errors.New("parameter priority cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{priority}", url.PathEscape(priority))
	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-09-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Get a PreRulesResource
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-09-01
//   - globalRulestackName - GlobalRulestack resource name
//   - priority - Pre Rule priority
//   - options - PreRulesClientGetOptions contains the optional parameters for the PreRulesClient.Get method.
func (client *PreRulesClient) Get(ctx context.Context, globalRulestackName string, priority string, options *PreRulesClientGetOptions) (PreRulesClientGetResponse, error) {
	var err error
	const operationName = "PreRulesClient.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, globalRulestackName, priority, options)
	if err != nil {
		return PreRulesClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return PreRulesClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return PreRulesClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *PreRulesClient) getCreateRequest(ctx context.Context, globalRulestackName string, priority string, options *PreRulesClientGetOptions) (*policy.Request, error) {
	urlPath := "/providers/PaloAltoNetworks.Cloudngfw/globalRulestacks/{globalRulestackName}/preRules/{priority}"
	if globalRulestackName == "" {
		return nil, errors.New("parameter globalRulestackName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{globalRulestackName}", url.PathEscape(globalRulestackName))
	if priority == "" {
		return nil, errors.New("parameter priority cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{priority}", url.PathEscape(priority))
	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-09-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// GetCounters - Get counters
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-09-01
//   - globalRulestackName - GlobalRulestack resource name
//   - priority - Pre Rule priority
//   - options - PreRulesClientGetCountersOptions contains the optional parameters for the PreRulesClient.GetCounters method.
func (client *PreRulesClient) GetCounters(ctx context.Context, globalRulestackName string, priority string, options *PreRulesClientGetCountersOptions) (PreRulesClientGetCountersResponse, error) {
	var err error
	const operationName = "PreRulesClient.GetCounters"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.getCountersCreateRequest(ctx, globalRulestackName, priority, options)
	if err != nil {
		return PreRulesClientGetCountersResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return PreRulesClientGetCountersResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return PreRulesClientGetCountersResponse{}, err
	}
	resp, err := client.getCountersHandleResponse(httpResp)
	return resp, err
}

// getCountersCreateRequest creates the GetCounters request.
func (client *PreRulesClient) getCountersCreateRequest(ctx context.Context, globalRulestackName string, priority string, options *PreRulesClientGetCountersOptions) (*policy.Request, error) {
	urlPath := "/providers/PaloAltoNetworks.Cloudngfw/globalRulestacks/{globalRulestackName}/preRules/{priority}/getCounters"
	if globalRulestackName == "" {
		return nil, errors.New("parameter globalRulestackName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{globalRulestackName}", url.PathEscape(globalRulestackName))
	if priority == "" {
		return nil, errors.New("parameter priority cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{priority}", url.PathEscape(priority))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2023-09-01")
	if options != nil && options.FirewallName != nil {
		reqQP.Set("firewallName", *options.FirewallName)
	}
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getCountersHandleResponse handles the GetCounters response.
func (client *PreRulesClient) getCountersHandleResponse(resp *http.Response) (PreRulesClientGetCountersResponse, error) {
	result := PreRulesClientGetCountersResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.RuleCounter); err != nil {
		return PreRulesClientGetCountersResponse{}, err
	}
	return result, nil
}

// NewListPager - List PreRulesResource resources by Tenant
//
// Generated from API version 2023-09-01
//   - globalRulestackName - GlobalRulestack resource name
//   - options - PreRulesClientListOptions contains the optional parameters for the PreRulesClient.NewListPager method.
func (client *PreRulesClient) NewListPager(globalRulestackName string, options *PreRulesClientListOptions) *runtime.Pager[PreRulesClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[PreRulesClientListResponse]{
		More: func(page PreRulesClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *PreRulesClientListResponse) (PreRulesClientListResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PreRulesClient.NewListPager")
			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.listCreateRequest(ctx, globalRulestackName, options)
			}, nil)
			if err != nil {
				return PreRulesClientListResponse{}, err
			}
			return client.listHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listCreateRequest creates the List request.
func (client *PreRulesClient) listCreateRequest(ctx context.Context, globalRulestackName string, options *PreRulesClientListOptions) (*policy.Request, error) {
	urlPath := "/providers/PaloAltoNetworks.Cloudngfw/globalRulestacks/{globalRulestackName}/preRules"
	if globalRulestackName == "" {
		return nil, errors.New("parameter globalRulestackName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{globalRulestackName}", url.PathEscape(globalRulestackName))
	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-09-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listHandleResponse handles the List response.
func (client *PreRulesClient) listHandleResponse(resp *http.Response) (PreRulesClientListResponse, error) {
	result := PreRulesClientListResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.PreRulesResourceListResult); err != nil {
		return PreRulesClientListResponse{}, err
	}
	return result, nil
}

// RefreshCounters - Refresh counters
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-09-01
//   - globalRulestackName - GlobalRulestack resource name
//   - priority - Pre Rule priority
//   - options - PreRulesClientRefreshCountersOptions contains the optional parameters for the PreRulesClient.RefreshCounters
//     method.
func (client *PreRulesClient) RefreshCounters(ctx context.Context, globalRulestackName string, priority string, options *PreRulesClientRefreshCountersOptions) (PreRulesClientRefreshCountersResponse, error) {
	var err error
	const operationName = "PreRulesClient.RefreshCounters"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.refreshCountersCreateRequest(ctx, globalRulestackName, priority, options)
	if err != nil {
		return PreRulesClientRefreshCountersResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return PreRulesClientRefreshCountersResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return PreRulesClientRefreshCountersResponse{}, err
	}
	return PreRulesClientRefreshCountersResponse{}, nil
}

// refreshCountersCreateRequest creates the RefreshCounters request.
func (client *PreRulesClient) refreshCountersCreateRequest(ctx context.Context, globalRulestackName string, priority string, options *PreRulesClientRefreshCountersOptions) (*policy.Request, error) {
	urlPath := "/providers/PaloAltoNetworks.Cloudngfw/globalRulestacks/{globalRulestackName}/preRules/{priority}/refreshCounters"
	if globalRulestackName == "" {
		return nil, errors.New("parameter globalRulestackName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{globalRulestackName}", url.PathEscape(globalRulestackName))
	if priority == "" {
		return nil, errors.New("parameter priority cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{priority}", url.PathEscape(priority))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2023-09-01")
	if options != nil && options.FirewallName != nil {
		reqQP.Set("firewallName", *options.FirewallName)
	}
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// ResetCounters - Reset counters
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2023-09-01
//   - globalRulestackName - GlobalRulestack resource name
//   - priority - Pre Rule priority
//   - options - PreRulesClientResetCountersOptions contains the optional parameters for the PreRulesClient.ResetCounters method.
func (client *PreRulesClient) ResetCounters(ctx context.Context, globalRulestackName string, priority string, options *PreRulesClientResetCountersOptions) (PreRulesClientResetCountersResponse, error) {
	var err error
	const operationName = "PreRulesClient.ResetCounters"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.resetCountersCreateRequest(ctx, globalRulestackName, priority, options)
	if err != nil {
		return PreRulesClientResetCountersResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return PreRulesClientResetCountersResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return PreRulesClientResetCountersResponse{}, err
	}
	resp, err := client.resetCountersHandleResponse(httpResp)
	return resp, err
}

// resetCountersCreateRequest creates the ResetCounters request.
func (client *PreRulesClient) resetCountersCreateRequest(ctx context.Context, globalRulestackName string, priority string, options *PreRulesClientResetCountersOptions) (*policy.Request, error) {
	urlPath := "/providers/PaloAltoNetworks.Cloudngfw/globalRulestacks/{globalRulestackName}/preRules/{priority}/resetCounters"
	if globalRulestackName == "" {
		return nil, errors.New("parameter globalRulestackName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{globalRulestackName}", url.PathEscape(globalRulestackName))
	if priority == "" {
		return nil, errors.New("parameter priority cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{priority}", url.PathEscape(priority))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2023-09-01")
	if options != nil && options.FirewallName != nil {
		reqQP.Set("firewallName", *options.FirewallName)
	}
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// resetCountersHandleResponse handles the ResetCounters response.
func (client *PreRulesClient) resetCountersHandleResponse(resp *http.Response) (PreRulesClientResetCountersResponse, error) {
	result := PreRulesClientResetCountersResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.RuleCounterReset); err != nil {
		return PreRulesClientResetCountersResponse{}, err
	}
	return result, nil
}
