package policy

// 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.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"context"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"github.com/Azure/go-autorest/autorest/validation"
	"github.com/Azure/go-autorest/tracing"
	"net/http"
)

// ExemptionsClient is the client for the Exemptions methods of the Policy service.
type ExemptionsClient struct {
	BaseClient
}

// NewExemptionsClient creates an instance of the ExemptionsClient client.
func NewExemptionsClient(subscriptionID string) ExemptionsClient {
	return NewExemptionsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

// NewExemptionsClientWithBaseURI creates an instance of the ExemptionsClient client using a custom endpoint.  Use this
// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewExemptionsClientWithBaseURI(baseURI string, subscriptionID string) ExemptionsClient {
	return ExemptionsClient{NewWithBaseURI(baseURI, subscriptionID)}
}

// CreateOrUpdate this operation creates or updates a policy exemption with the given scope and name. Policy exemptions
// apply to all resources contained within their scope. For example, when you create a policy exemption at resource
// group scope for a policy assignment at the same or above level, the exemption exempts to all applicable resources in
// the resource group.
// Parameters:
// scope - the scope of the policy exemption. Valid scopes are: management group (format:
// '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format:
// '/subscriptions/{subscriptionId}'), resource group (format:
// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format:
// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'
// policyExemptionName - the name of the policy exemption to delete.
// parameters - parameters for the policy exemption.
func (client ExemptionsClient) CreateOrUpdate(ctx context.Context, scope string, policyExemptionName string, parameters Exemption) (result Exemption, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ExemptionsClient.CreateOrUpdate")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	if err := validation.Validate([]validation.Validation{
		{TargetValue: parameters,
			Constraints: []validation.Constraint{{Target: "parameters.ExemptionProperties", Name: validation.Null, Rule: true,
				Chain: []validation.Constraint{{Target: "parameters.ExemptionProperties.PolicyAssignmentID", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil {
		return result, validation.NewError("policy.ExemptionsClient", "CreateOrUpdate", err.Error())
	}

	req, err := client.CreateOrUpdatePreparer(ctx, scope, policyExemptionName, parameters)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "CreateOrUpdate", nil, "Failure preparing request")
		return
	}

	resp, err := client.CreateOrUpdateSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "CreateOrUpdate", resp, "Failure sending request")
		return
	}

	result, err = client.CreateOrUpdateResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "CreateOrUpdate", resp, "Failure responding to request")
		return
	}

	return
}

// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client ExemptionsClient) CreateOrUpdatePreparer(ctx context.Context, scope string, policyExemptionName string, parameters Exemption) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"policyExemptionName": autorest.Encode("path", policyExemptionName),
		"scope":               scope,
	}

	const APIVersion = "2020-07-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	parameters.SystemData = nil
	parameters.ID = nil
	parameters.Name = nil
	parameters.Type = nil
	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/json; charset=utf-8"),
		autorest.AsPut(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}", pathParameters),
		autorest.WithJSON(parameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client ExemptionsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {
	return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client ExemptionsClient) CreateOrUpdateResponder(resp *http.Response) (result Exemption, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// Delete this operation deletes a policy exemption, given its name and the scope it was created in. The scope of a
// policy exemption is the part of its ID preceding
// '/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}'.
// Parameters:
// scope - the scope of the policy exemption. Valid scopes are: management group (format:
// '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format:
// '/subscriptions/{subscriptionId}'), resource group (format:
// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format:
// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'
// policyExemptionName - the name of the policy exemption to delete.
func (client ExemptionsClient) Delete(ctx context.Context, scope string, policyExemptionName string) (result autorest.Response, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ExemptionsClient.Delete")
		defer func() {
			sc := -1
			if result.Response != nil {
				sc = result.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.DeletePreparer(ctx, scope, policyExemptionName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "Delete", nil, "Failure preparing request")
		return
	}

	resp, err := client.DeleteSender(req)
	if err != nil {
		result.Response = resp
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "Delete", resp, "Failure sending request")
		return
	}

	result, err = client.DeleteResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "Delete", resp, "Failure responding to request")
		return
	}

	return
}

// DeletePreparer prepares the Delete request.
func (client ExemptionsClient) DeletePreparer(ctx context.Context, scope string, policyExemptionName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"policyExemptionName": autorest.Encode("path", policyExemptionName),
		"scope":               scope,
	}

	const APIVersion = "2020-07-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsDelete(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client ExemptionsClient) DeleteSender(req *http.Request) (*http.Response, error) {
	return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client ExemptionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
		autorest.ByClosing())
	result.Response = resp
	return
}

// Get this operation retrieves a single policy exemption, given its name and the scope it was created at.
// Parameters:
// scope - the scope of the policy exemption. Valid scopes are: management group (format:
// '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format:
// '/subscriptions/{subscriptionId}'), resource group (format:
// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format:
// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'
// policyExemptionName - the name of the policy exemption to delete.
func (client ExemptionsClient) Get(ctx context.Context, scope string, policyExemptionName string) (result Exemption, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ExemptionsClient.Get")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.GetPreparer(ctx, scope, policyExemptionName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "Get", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "Get", resp, "Failure sending request")
		return
	}

	result, err = client.GetResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "Get", resp, "Failure responding to request")
		return
	}

	return
}

// GetPreparer prepares the Get request.
func (client ExemptionsClient) GetPreparer(ctx context.Context, scope string, policyExemptionName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"policyExemptionName": autorest.Encode("path", policyExemptionName),
		"scope":               scope,
	}

	const APIVersion = "2020-07-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client ExemptionsClient) GetSender(req *http.Request) (*http.Response, error) {
	return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client ExemptionsClient) GetResponder(resp *http.Response) (result Exemption, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// List this operation retrieves the list of all policy exemptions associated with the given subscription that match
// the optional given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()', 'excludeExpired()' or
// 'policyAssignmentId eq '{value}”. If $filter is not provided, the unfiltered list includes all policy exemptions
// associated with the subscription, including those that apply directly or from management groups that contain the
// given subscription, as well as any applied to objects contained within the subscription.
// Parameters:
// filter - the filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()',
// 'excludeExpired()' or 'policyAssignmentId eq '{value}”. If $filter is not provided, no filtering is
// performed. If $filter is not provided, the unfiltered list includes all policy exemptions associated with
// the scope, including those that apply directly or apply from containing scopes. If $filter=atScope() is
// provided, the returned list only includes all policy exemptions that apply to the scope, which is everything
// in the unfiltered list except those applied to sub scopes contained within the given scope. If
// $filter=atExactScope() is provided, the returned list only includes all policy exemptions that at the given
// scope. If $filter=excludeExpired() is provided, the returned list only includes all policy exemptions that
// either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq '{value}' is
// provided. the returned list only includes all policy exemptions that are associated with the give
// policyAssignmentId.
func (client ExemptionsClient) List(ctx context.Context, filter string) (result ExemptionListResultPage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ExemptionsClient.List")
		defer func() {
			sc := -1
			if result.elr.Response.Response != nil {
				sc = result.elr.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.fn = client.listNextResults
	req, err := client.ListPreparer(ctx, filter)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "List", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListSender(req)
	if err != nil {
		result.elr.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "List", resp, "Failure sending request")
		return
	}

	result.elr, err = client.ListResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "List", resp, "Failure responding to request")
		return
	}
	if result.elr.hasNextLink() && result.elr.IsEmpty() {
		err = result.NextWithContext(ctx)
		return
	}

	return
}

// ListPreparer prepares the List request.
func (client ExemptionsClient) ListPreparer(ctx context.Context, filter string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"subscriptionId": autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2020-07-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}
	if len(filter) > 0 {
		queryParameters["$filter"] = filter
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyExemptions", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client ExemptionsClient) ListSender(req *http.Request) (*http.Response, error) {
	return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}

// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client ExemptionsClient) ListResponder(resp *http.Response) (result ExemptionListResult, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// listNextResults retrieves the next set of results, if any.
func (client ExemptionsClient) listNextResults(ctx context.Context, lastResults ExemptionListResult) (result ExemptionListResult, err error) {
	req, err := lastResults.exemptionListResultPreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "policy.ExemptionsClient", "listNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "policy.ExemptionsClient", "listNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "listNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client ExemptionsClient) ListComplete(ctx context.Context, filter string) (result ExemptionListResultIterator, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ExemptionsClient.List")
		defer func() {
			sc := -1
			if result.Response().Response.Response != nil {
				sc = result.page.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.page, err = client.List(ctx, filter)
	return
}

// ListForManagementGroup this operation retrieves the list of all policy exemptions applicable to the management group
// that match the given $filter. Valid values for $filter are: 'atScope()', 'atExactScope()', 'excludeExpired()' or
// 'policyAssignmentId eq '{value}”. If $filter=atScope() is provided, the returned list includes all policy
// exemptions that are assigned to the management group or the management group's ancestors.
// Parameters:
// managementGroupID - the ID of the management group.
// filter - the filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()',
// 'excludeExpired()' or 'policyAssignmentId eq '{value}”. If $filter is not provided, no filtering is
// performed. If $filter is not provided, the unfiltered list includes all policy exemptions associated with
// the scope, including those that apply directly or apply from containing scopes. If $filter=atScope() is
// provided, the returned list only includes all policy exemptions that apply to the scope, which is everything
// in the unfiltered list except those applied to sub scopes contained within the given scope. If
// $filter=atExactScope() is provided, the returned list only includes all policy exemptions that at the given
// scope. If $filter=excludeExpired() is provided, the returned list only includes all policy exemptions that
// either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq '{value}' is
// provided. the returned list only includes all policy exemptions that are associated with the give
// policyAssignmentId.
func (client ExemptionsClient) ListForManagementGroup(ctx context.Context, managementGroupID string, filter string) (result ExemptionListResultPage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ExemptionsClient.ListForManagementGroup")
		defer func() {
			sc := -1
			if result.elr.Response.Response != nil {
				sc = result.elr.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.fn = client.listForManagementGroupNextResults
	req, err := client.ListForManagementGroupPreparer(ctx, managementGroupID, filter)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "ListForManagementGroup", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListForManagementGroupSender(req)
	if err != nil {
		result.elr.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "ListForManagementGroup", resp, "Failure sending request")
		return
	}

	result.elr, err = client.ListForManagementGroupResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "ListForManagementGroup", resp, "Failure responding to request")
		return
	}
	if result.elr.hasNextLink() && result.elr.IsEmpty() {
		err = result.NextWithContext(ctx)
		return
	}

	return
}

// ListForManagementGroupPreparer prepares the ListForManagementGroup request.
func (client ExemptionsClient) ListForManagementGroupPreparer(ctx context.Context, managementGroupID string, filter string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"managementGroupId": autorest.Encode("path", managementGroupID),
	}

	const APIVersion = "2020-07-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}
	if len(filter) > 0 {
		queryParameters["$filter"] = filter
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyExemptions", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListForManagementGroupSender sends the ListForManagementGroup request. The method will close the
// http.Response Body if it receives an error.
func (client ExemptionsClient) ListForManagementGroupSender(req *http.Request) (*http.Response, error) {
	return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// ListForManagementGroupResponder handles the response to the ListForManagementGroup request. The method always
// closes the http.Response Body.
func (client ExemptionsClient) ListForManagementGroupResponder(resp *http.Response) (result ExemptionListResult, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// listForManagementGroupNextResults retrieves the next set of results, if any.
func (client ExemptionsClient) listForManagementGroupNextResults(ctx context.Context, lastResults ExemptionListResult) (result ExemptionListResult, err error) {
	req, err := lastResults.exemptionListResultPreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "policy.ExemptionsClient", "listForManagementGroupNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListForManagementGroupSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "policy.ExemptionsClient", "listForManagementGroupNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListForManagementGroupResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "listForManagementGroupNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListForManagementGroupComplete enumerates all values, automatically crossing page boundaries as required.
func (client ExemptionsClient) ListForManagementGroupComplete(ctx context.Context, managementGroupID string, filter string) (result ExemptionListResultIterator, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ExemptionsClient.ListForManagementGroup")
		defer func() {
			sc := -1
			if result.Response().Response.Response != nil {
				sc = result.page.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.page, err = client.ListForManagementGroup(ctx, managementGroupID, filter)
	return
}

// ListForResource this operation retrieves the list of all policy exemptions associated with the specified resource in
// the given resource group and subscription that match the optional given $filter. Valid values for $filter are:
// 'atScope()', 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}”. If $filter is not provided,
// the unfiltered list includes all policy exemptions associated with the resource, including those that apply directly
// or from all containing scopes, as well as any applied to resources contained within the resource. Three parameters
// plus the resource name are used to identify a specific resource. If the resource is not part of a parent resource
// (the more common case), the parent resource path should not be provided (or provided as ”). For example a web app
// could be specified as ({resourceProviderNamespace} == 'Microsoft.Web', {parentResourcePath} == ”, {resourceType} ==
// 'sites', {resourceName} == 'MyWebApp'). If the resource is part of a parent resource, then all parameters should be
// provided. For example a virtual machine DNS name could be specified as ({resourceProviderNamespace} ==
// 'Microsoft.Compute', {parentResourcePath} == 'virtualMachines/MyVirtualMachine', {resourceType} == 'domainNames',
// {resourceName} == 'MyComputerName'). A convenient alternative to providing the namespace and type name separately is
// to provide both in the {resourceType} parameter, format: ({resourceProviderNamespace} == ”, {parentResourcePath} ==
// ”, {resourceType} == 'Microsoft.Web/sites', {resourceName} == 'MyWebApp').
// Parameters:
// resourceGroupName - the name of the resource group containing the resource.
// resourceProviderNamespace - the namespace of the resource provider. For example, the namespace of a virtual
// machine is Microsoft.Compute (from Microsoft.Compute/virtualMachines)
// parentResourcePath - the parent resource path. Use empty string if there is none.
// resourceType - the resource type name. For example the type name of a web app is 'sites' (from
// Microsoft.Web/sites).
// resourceName - the name of the resource.
// filter - the filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()',
// 'excludeExpired()' or 'policyAssignmentId eq '{value}”. If $filter is not provided, no filtering is
// performed. If $filter is not provided, the unfiltered list includes all policy exemptions associated with
// the scope, including those that apply directly or apply from containing scopes. If $filter=atScope() is
// provided, the returned list only includes all policy exemptions that apply to the scope, which is everything
// in the unfiltered list except those applied to sub scopes contained within the given scope. If
// $filter=atExactScope() is provided, the returned list only includes all policy exemptions that at the given
// scope. If $filter=excludeExpired() is provided, the returned list only includes all policy exemptions that
// either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq '{value}' is
// provided. the returned list only includes all policy exemptions that are associated with the give
// policyAssignmentId.
func (client ExemptionsClient) ListForResource(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, filter string) (result ExemptionListResultPage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ExemptionsClient.ListForResource")
		defer func() {
			sc := -1
			if result.elr.Response.Response != nil {
				sc = result.elr.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	if err := validation.Validate([]validation.Validation{
		{TargetValue: resourceGroupName,
			Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
				{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
				{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
		return result, validation.NewError("policy.ExemptionsClient", "ListForResource", err.Error())
	}

	result.fn = client.listForResourceNextResults
	req, err := client.ListForResourcePreparer(ctx, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "ListForResource", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListForResourceSender(req)
	if err != nil {
		result.elr.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "ListForResource", resp, "Failure sending request")
		return
	}

	result.elr, err = client.ListForResourceResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "ListForResource", resp, "Failure responding to request")
		return
	}
	if result.elr.hasNextLink() && result.elr.IsEmpty() {
		err = result.NextWithContext(ctx)
		return
	}

	return
}

// ListForResourcePreparer prepares the ListForResource request.
func (client ExemptionsClient) ListForResourcePreparer(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, filter string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"parentResourcePath":        parentResourcePath,
		"resourceGroupName":         autorest.Encode("path", resourceGroupName),
		"resourceName":              autorest.Encode("path", resourceName),
		"resourceProviderNamespace": autorest.Encode("path", resourceProviderNamespace),
		"resourceType":              resourceType,
		"subscriptionId":            autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2020-07-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}
	if len(filter) > 0 {
		queryParameters["$filter"] = filter
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyExemptions", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListForResourceSender sends the ListForResource request. The method will close the
// http.Response Body if it receives an error.
func (client ExemptionsClient) ListForResourceSender(req *http.Request) (*http.Response, error) {
	return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}

// ListForResourceResponder handles the response to the ListForResource request. The method always
// closes the http.Response Body.
func (client ExemptionsClient) ListForResourceResponder(resp *http.Response) (result ExemptionListResult, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// listForResourceNextResults retrieves the next set of results, if any.
func (client ExemptionsClient) listForResourceNextResults(ctx context.Context, lastResults ExemptionListResult) (result ExemptionListResult, err error) {
	req, err := lastResults.exemptionListResultPreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "policy.ExemptionsClient", "listForResourceNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListForResourceSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "policy.ExemptionsClient", "listForResourceNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListForResourceResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "listForResourceNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListForResourceComplete enumerates all values, automatically crossing page boundaries as required.
func (client ExemptionsClient) ListForResourceComplete(ctx context.Context, resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, filter string) (result ExemptionListResultIterator, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ExemptionsClient.ListForResource")
		defer func() {
			sc := -1
			if result.Response().Response.Response != nil {
				sc = result.page.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.page, err = client.ListForResource(ctx, resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter)
	return
}

// ListForResourceGroup this operation retrieves the list of all policy exemptions associated with the given resource
// group in the given subscription that match the optional given $filter. Valid values for $filter are: 'atScope()',
// 'atExactScope()', 'excludeExpired()' or 'policyAssignmentId eq '{value}”. If $filter is not provided, the
// unfiltered list includes all policy exemptions associated with the resource group, including those that apply
// directly or apply from containing scopes, as well as any applied to resources contained within the resource group.
// Parameters:
// resourceGroupName - the name of the resource group containing the resource.
// filter - the filter to apply on the operation. Valid values for $filter are: 'atScope()', 'atExactScope()',
// 'excludeExpired()' or 'policyAssignmentId eq '{value}”. If $filter is not provided, no filtering is
// performed. If $filter is not provided, the unfiltered list includes all policy exemptions associated with
// the scope, including those that apply directly or apply from containing scopes. If $filter=atScope() is
// provided, the returned list only includes all policy exemptions that apply to the scope, which is everything
// in the unfiltered list except those applied to sub scopes contained within the given scope. If
// $filter=atExactScope() is provided, the returned list only includes all policy exemptions that at the given
// scope. If $filter=excludeExpired() is provided, the returned list only includes all policy exemptions that
// either haven't expired or didn't set expiration date. If $filter=policyAssignmentId eq '{value}' is
// provided. the returned list only includes all policy exemptions that are associated with the give
// policyAssignmentId.
func (client ExemptionsClient) ListForResourceGroup(ctx context.Context, resourceGroupName string, filter string) (result ExemptionListResultPage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ExemptionsClient.ListForResourceGroup")
		defer func() {
			sc := -1
			if result.elr.Response.Response != nil {
				sc = result.elr.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	if err := validation.Validate([]validation.Validation{
		{TargetValue: resourceGroupName,
			Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
				{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
				{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
		return result, validation.NewError("policy.ExemptionsClient", "ListForResourceGroup", err.Error())
	}

	result.fn = client.listForResourceGroupNextResults
	req, err := client.ListForResourceGroupPreparer(ctx, resourceGroupName, filter)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "ListForResourceGroup", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListForResourceGroupSender(req)
	if err != nil {
		result.elr.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "ListForResourceGroup", resp, "Failure sending request")
		return
	}

	result.elr, err = client.ListForResourceGroupResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "ListForResourceGroup", resp, "Failure responding to request")
		return
	}
	if result.elr.hasNextLink() && result.elr.IsEmpty() {
		err = result.NextWithContext(ctx)
		return
	}

	return
}

// ListForResourceGroupPreparer prepares the ListForResourceGroup request.
func (client ExemptionsClient) ListForResourceGroupPreparer(ctx context.Context, resourceGroupName string, filter string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2020-07-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}
	if len(filter) > 0 {
		queryParameters["$filter"] = filter
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyExemptions", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListForResourceGroupSender sends the ListForResourceGroup request. The method will close the
// http.Response Body if it receives an error.
func (client ExemptionsClient) ListForResourceGroupSender(req *http.Request) (*http.Response, error) {
	return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}

// ListForResourceGroupResponder handles the response to the ListForResourceGroup request. The method always
// closes the http.Response Body.
func (client ExemptionsClient) ListForResourceGroupResponder(resp *http.Response) (result ExemptionListResult, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// listForResourceGroupNextResults retrieves the next set of results, if any.
func (client ExemptionsClient) listForResourceGroupNextResults(ctx context.Context, lastResults ExemptionListResult) (result ExemptionListResult, err error) {
	req, err := lastResults.exemptionListResultPreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "policy.ExemptionsClient", "listForResourceGroupNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListForResourceGroupSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "policy.ExemptionsClient", "listForResourceGroupNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListForResourceGroupResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "policy.ExemptionsClient", "listForResourceGroupNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListForResourceGroupComplete enumerates all values, automatically crossing page boundaries as required.
func (client ExemptionsClient) ListForResourceGroupComplete(ctx context.Context, resourceGroupName string, filter string) (result ExemptionListResultIterator, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ExemptionsClient.ListForResourceGroup")
		defer func() {
			sc := -1
			if result.Response().Response.Response != nil {
				sc = result.page.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.page, err = client.ListForResourceGroup(ctx, resourceGroupName, filter)
	return
}
