package apimanagement

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

// OperationClient is the apiManagement Client
type OperationClient struct {
	BaseClient
}

// NewOperationClient creates an instance of the OperationClient client.
func NewOperationClient(subscriptionID string) OperationClient {
	return NewOperationClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

// NewOperationClientWithBaseURI creates an instance of the OperationClient 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 NewOperationClientWithBaseURI(baseURI string, subscriptionID string) OperationClient {
	return OperationClient{NewWithBaseURI(baseURI, subscriptionID)}
}

// ListByTags lists a collection of operations associated with tags.
// Parameters:
// resourceGroupName - the name of the resource group.
// serviceName - the name of the API Management service.
// apiid - API revision identifier. Must be unique in the current API Management service instance. Non-current
// revision has ;rev=n as a suffix where n is the revision number.
// filter - |   Field     |     Usage     |     Supported operators     |     Supported functions
// |</br>|-------------|-------------|-------------|-------------|</br>| name | filter | ge, le, eq, ne, gt, lt
// | substringof, contains, startswith, endswith | </br>| displayName | filter | ge, le, eq, ne, gt, lt |
// substringof, contains, startswith, endswith | </br>| apiName | filter | ge, le, eq, ne, gt, lt |
// substringof, contains, startswith, endswith | </br>| description | filter | ge, le, eq, ne, gt, lt |
// substringof, contains, startswith, endswith | </br>| method | filter | ge, le, eq, ne, gt, lt | substringof,
// contains, startswith, endswith | </br>| urlTemplate | filter | ge, le, eq, ne, gt, lt | substringof,
// contains, startswith, endswith | </br>
// top - number of records to return.
// skip - number of records to skip.
// includeNotTaggedOperations - include not tagged Operations.
func (client OperationClient) ListByTags(ctx context.Context, resourceGroupName string, serviceName string, apiid string, filter string, top *int32, skip *int32, includeNotTaggedOperations *bool) (result TagResourceCollectionPage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/OperationClient.ListByTags")
		defer func() {
			sc := -1
			if result.trc.Response.Response != nil {
				sc = result.trc.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	if err := validation.Validate([]validation.Validation{
		{TargetValue: serviceName,
			Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
				{Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil},
				{Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}},
		{TargetValue: apiid,
			Constraints: []validation.Constraint{{Target: "apiid", Name: validation.MaxLength, Rule: 256, Chain: nil},
				{Target: "apiid", Name: validation.MinLength, Rule: 1, Chain: nil},
				{Target: "apiid", Name: validation.Pattern, Rule: `^[^*#&+:<>?]+$`, Chain: nil}}},
		{TargetValue: top,
			Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false,
				Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}}}}},
		{TargetValue: skip,
			Constraints: []validation.Constraint{{Target: "skip", Name: validation.Null, Rule: false,
				Chain: []validation.Constraint{{Target: "skip", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil {
		return result, validation.NewError("apimanagement.OperationClient", "ListByTags", err.Error())
	}

	result.fn = client.listByTagsNextResults
	req, err := client.ListByTagsPreparer(ctx, resourceGroupName, serviceName, apiid, filter, top, skip, includeNotTaggedOperations)
	if err != nil {
		err = autorest.NewErrorWithError(err, "apimanagement.OperationClient", "ListByTags", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListByTagsSender(req)
	if err != nil {
		result.trc.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "apimanagement.OperationClient", "ListByTags", resp, "Failure sending request")
		return
	}

	result.trc, err = client.ListByTagsResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "apimanagement.OperationClient", "ListByTags", resp, "Failure responding to request")
		return
	}
	if result.trc.hasNextLink() && result.trc.IsEmpty() {
		err = result.NextWithContext(ctx)
		return
	}

	return
}

// ListByTagsPreparer prepares the ListByTags request.
func (client OperationClient) ListByTagsPreparer(ctx context.Context, resourceGroupName string, serviceName string, apiid string, filter string, top *int32, skip *int32, includeNotTaggedOperations *bool) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"apiId":             autorest.Encode("path", apiid),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"serviceName":       autorest.Encode("path", serviceName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2019-12-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}
	if len(filter) > 0 {
		queryParameters["$filter"] = autorest.Encode("query", filter)
	}
	if top != nil {
		queryParameters["$top"] = autorest.Encode("query", *top)
	}
	if skip != nil {
		queryParameters["$skip"] = autorest.Encode("query", *skip)
	}
	if includeNotTaggedOperations != nil {
		queryParameters["includeNotTaggedOperations"] = autorest.Encode("query", *includeNotTaggedOperations)
	}

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

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

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

// listByTagsNextResults retrieves the next set of results, if any.
func (client OperationClient) listByTagsNextResults(ctx context.Context, lastResults TagResourceCollection) (result TagResourceCollection, err error) {
	req, err := lastResults.tagResourceCollectionPreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "apimanagement.OperationClient", "listByTagsNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListByTagsSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "apimanagement.OperationClient", "listByTagsNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListByTagsResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "apimanagement.OperationClient", "listByTagsNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListByTagsComplete enumerates all values, automatically crossing page boundaries as required.
func (client OperationClient) ListByTagsComplete(ctx context.Context, resourceGroupName string, serviceName string, apiid string, filter string, top *int32, skip *int32, includeNotTaggedOperations *bool) (result TagResourceCollectionIterator, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/OperationClient.ListByTags")
		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.ListByTags(ctx, resourceGroupName, serviceName, apiid, filter, top, skip, includeNotTaggedOperations)
	return
}
