package sql

// 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/tracing"
	"net/http"
)

// ManagedDatabaseQueriesClient is the the Azure SQL Database management API provides a RESTful set of web services
// that interact with Azure SQL Database services to manage your databases. The API enables you to create, retrieve,
// update, and delete databases.
type ManagedDatabaseQueriesClient struct {
	BaseClient
}

// NewManagedDatabaseQueriesClient creates an instance of the ManagedDatabaseQueriesClient client.
func NewManagedDatabaseQueriesClient(subscriptionID string) ManagedDatabaseQueriesClient {
	return NewManagedDatabaseQueriesClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

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

// Get get query by query id.
// Parameters:
// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value
// from the Azure Resource Manager API or the portal.
// managedInstanceName - the name of the managed instance.
// databaseName - the name of the database.
func (client ManagedDatabaseQueriesClient) Get(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, queryID string) (result ManagedInstanceQuery, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ManagedDatabaseQueriesClient.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, resourceGroupName, managedInstanceName, databaseName, queryID)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseQueriesClient", "Get", nil, "Failure preparing request")
		return
	}

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

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

	return
}

// GetPreparer prepares the Get request.
func (client ManagedDatabaseQueriesClient) GetPreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, queryID string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"databaseName":        autorest.Encode("path", databaseName),
		"managedInstanceName": autorest.Encode("path", managedInstanceName),
		"queryId":             autorest.Encode("path", queryID),
		"resourceGroupName":   autorest.Encode("path", resourceGroupName),
		"subscriptionId":      autorest.Encode("path", client.SubscriptionID),
	}

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

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}", 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 ManagedDatabaseQueriesClient) GetSender(req *http.Request) (*http.Response, error) {
	return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}

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

// ListByQuery get query execution statistics by query id.
// Parameters:
// resourceGroupName - the name of the resource group that contains the resource. You can obtain this value
// from the Azure Resource Manager API or the portal.
// managedInstanceName - the name of the managed instance.
// databaseName - the name of the database.
// startTime - start time for observed period.
// endTime - end time for observed period.
// interval - the time step to be used to summarize the metric values.
func (client ManagedDatabaseQueriesClient) ListByQuery(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, queryID string, startTime string, endTime string, interval QueryTimeGrainType) (result ManagedInstanceQueryStatisticsPage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ManagedDatabaseQueriesClient.ListByQuery")
		defer func() {
			sc := -1
			if result.miqs.Response.Response != nil {
				sc = result.miqs.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.fn = client.listByQueryNextResults
	req, err := client.ListByQueryPreparer(ctx, resourceGroupName, managedInstanceName, databaseName, queryID, startTime, endTime, interval)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseQueriesClient", "ListByQuery", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListByQuerySender(req)
	if err != nil {
		result.miqs.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseQueriesClient", "ListByQuery", resp, "Failure sending request")
		return
	}

	result.miqs, err = client.ListByQueryResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseQueriesClient", "ListByQuery", resp, "Failure responding to request")
		return
	}
	if result.miqs.hasNextLink() && result.miqs.IsEmpty() {
		err = result.NextWithContext(ctx)
		return
	}

	return
}

// ListByQueryPreparer prepares the ListByQuery request.
func (client ManagedDatabaseQueriesClient) ListByQueryPreparer(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, queryID string, startTime string, endTime string, interval QueryTimeGrainType) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"databaseName":        autorest.Encode("path", databaseName),
		"managedInstanceName": autorest.Encode("path", managedInstanceName),
		"queryId":             autorest.Encode("path", queryID),
		"resourceGroupName":   autorest.Encode("path", resourceGroupName),
		"subscriptionId":      autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2020-11-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}
	if len(startTime) > 0 {
		queryParameters["startTime"] = autorest.Encode("query", startTime)
	}
	if len(endTime) > 0 {
		queryParameters["endTime"] = autorest.Encode("query", endTime)
	}
	if len(string(interval)) > 0 {
		queryParameters["interval"] = autorest.Encode("query", interval)
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}/statistics", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

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

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

// listByQueryNextResults retrieves the next set of results, if any.
func (client ManagedDatabaseQueriesClient) listByQueryNextResults(ctx context.Context, lastResults ManagedInstanceQueryStatistics) (result ManagedInstanceQueryStatistics, err error) {
	req, err := lastResults.managedInstanceQueryStatisticsPreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "sql.ManagedDatabaseQueriesClient", "listByQueryNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListByQuerySender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "sql.ManagedDatabaseQueriesClient", "listByQueryNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListByQueryResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseQueriesClient", "listByQueryNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListByQueryComplete enumerates all values, automatically crossing page boundaries as required.
func (client ManagedDatabaseQueriesClient) ListByQueryComplete(ctx context.Context, resourceGroupName string, managedInstanceName string, databaseName string, queryID string, startTime string, endTime string, interval QueryTimeGrainType) (result ManagedInstanceQueryStatisticsIterator, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ManagedDatabaseQueriesClient.ListByQuery")
		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.ListByQuery(ctx, resourceGroupName, managedInstanceName, databaseName, queryID, startTime, endTime, interval)
	return
}
