package sql

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// 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"
)

// DatabaseVulnerabilityAssessmentScansClient 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 DatabaseVulnerabilityAssessmentScansClient struct {
	BaseClient
}

// NewDatabaseVulnerabilityAssessmentScansClient creates an instance of the DatabaseVulnerabilityAssessmentScansClient
// client.
func NewDatabaseVulnerabilityAssessmentScansClient(subscriptionID string) DatabaseVulnerabilityAssessmentScansClient {
	return NewDatabaseVulnerabilityAssessmentScansClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

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

// Export convert an existing scan result to a human readable format. If already exists nothing happens
// 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.
// serverName - the name of the server.
// databaseName - the name of the scanned database.
// scanID - the vulnerability assessment scan Id.
func (client DatabaseVulnerabilityAssessmentScansClient) Export(ctx context.Context, resourceGroupName string, serverName string, databaseName string, scanID string) (result DatabaseVulnerabilityAssessmentScansExport, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/DatabaseVulnerabilityAssessmentScansClient.Export")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.ExportPreparer(ctx, resourceGroupName, serverName, databaseName, scanID)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "Export", nil, "Failure preparing request")
		return
	}

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

	result, err = client.ExportResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "Export", resp, "Failure responding to request")
		return
	}

	return
}

// ExportPreparer prepares the Export request.
func (client DatabaseVulnerabilityAssessmentScansClient) ExportPreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string, scanID string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"databaseName":                autorest.Encode("path", databaseName),
		"resourceGroupName":           autorest.Encode("path", resourceGroupName),
		"scanId":                      autorest.Encode("path", scanID),
		"serverName":                  autorest.Encode("path", serverName),
		"subscriptionId":              autorest.Encode("path", client.SubscriptionID),
		"vulnerabilityAssessmentName": autorest.Encode("path", "default"),
	}

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

	preparer := autorest.CreatePreparer(
		autorest.AsPost(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans/{scanId}/export", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

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

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

// Get gets a vulnerability assessment scan record of a database.
// 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.
// serverName - the name of the server.
// databaseName - the name of the database.
// scanID - the vulnerability assessment scan Id of the scan to retrieve.
func (client DatabaseVulnerabilityAssessmentScansClient) Get(ctx context.Context, resourceGroupName string, serverName string, databaseName string, scanID string) (result VulnerabilityAssessmentScanRecord, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/DatabaseVulnerabilityAssessmentScansClient.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, serverName, databaseName, scanID)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "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.DatabaseVulnerabilityAssessmentScansClient", "Get", resp, "Failure sending request")
		return
	}

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

	return
}

// GetPreparer prepares the Get request.
func (client DatabaseVulnerabilityAssessmentScansClient) GetPreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string, scanID string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"databaseName":                autorest.Encode("path", databaseName),
		"resourceGroupName":           autorest.Encode("path", resourceGroupName),
		"scanId":                      autorest.Encode("path", scanID),
		"serverName":                  autorest.Encode("path", serverName),
		"subscriptionId":              autorest.Encode("path", client.SubscriptionID),
		"vulnerabilityAssessmentName": autorest.Encode("path", "default"),
	}

	const APIVersion = "2017-10-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/servers/{serverName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans/{scanId}", 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 DatabaseVulnerabilityAssessmentScansClient) 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 DatabaseVulnerabilityAssessmentScansClient) GetResponder(resp *http.Response) (result VulnerabilityAssessmentScanRecord, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// InitiateScan executes a Vulnerability Assessment database scan.
// 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.
// serverName - the name of the server.
// databaseName - the name of the database.
// scanID - the vulnerability assessment scan Id of the scan to retrieve.
func (client DatabaseVulnerabilityAssessmentScansClient) InitiateScan(ctx context.Context, resourceGroupName string, serverName string, databaseName string, scanID string) (result DatabaseVulnerabilityAssessmentScansInitiateScanFuture, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/DatabaseVulnerabilityAssessmentScansClient.InitiateScan")
		defer func() {
			sc := -1
			if result.FutureAPI != nil && result.FutureAPI.Response() != nil {
				sc = result.FutureAPI.Response().StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.InitiateScanPreparer(ctx, resourceGroupName, serverName, databaseName, scanID)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "InitiateScan", nil, "Failure preparing request")
		return
	}

	result, err = client.InitiateScanSender(req)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "InitiateScan", nil, "Failure sending request")
		return
	}

	return
}

// InitiateScanPreparer prepares the InitiateScan request.
func (client DatabaseVulnerabilityAssessmentScansClient) InitiateScanPreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string, scanID string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"databaseName":                autorest.Encode("path", databaseName),
		"resourceGroupName":           autorest.Encode("path", resourceGroupName),
		"scanId":                      autorest.Encode("path", scanID),
		"serverName":                  autorest.Encode("path", serverName),
		"subscriptionId":              autorest.Encode("path", client.SubscriptionID),
		"vulnerabilityAssessmentName": autorest.Encode("path", "default"),
	}

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

	preparer := autorest.CreatePreparer(
		autorest.AsPost(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans/{scanId}/initiateScan", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// InitiateScanSender sends the InitiateScan request. The method will close the
// http.Response Body if it receives an error.
func (client DatabaseVulnerabilityAssessmentScansClient) InitiateScanSender(req *http.Request) (future DatabaseVulnerabilityAssessmentScansInitiateScanFuture, err error) {
	var resp *http.Response
	resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
	if err != nil {
		return
	}
	var azf azure.Future
	azf, err = azure.NewFutureFromResponse(resp)
	future.FutureAPI = &azf
	future.Result = func(client DatabaseVulnerabilityAssessmentScansClient) (ar autorest.Response, err error) {
		var done bool
		done, err = future.DoneWithContext(context.Background(), client)
		if err != nil {
			err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansInitiateScanFuture", "Result", future.Response(), "Polling failure")
			return
		}
		if !done {
			err = azure.NewAsyncOpIncompleteError("sql.DatabaseVulnerabilityAssessmentScansInitiateScanFuture")
			return
		}
		ar.Response = future.Response()
		return
	}
	return
}

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

// ListByDatabase lists the vulnerability assessment scans of a database.
// 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.
// serverName - the name of the server.
// databaseName - the name of the database.
func (client DatabaseVulnerabilityAssessmentScansClient) ListByDatabase(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (result VulnerabilityAssessmentScanRecordListResultPage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/DatabaseVulnerabilityAssessmentScansClient.ListByDatabase")
		defer func() {
			sc := -1
			if result.vasrlr.Response.Response != nil {
				sc = result.vasrlr.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.fn = client.listByDatabaseNextResults
	req, err := client.ListByDatabasePreparer(ctx, resourceGroupName, serverName, databaseName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "ListByDatabase", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListByDatabaseSender(req)
	if err != nil {
		result.vasrlr.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "ListByDatabase", resp, "Failure sending request")
		return
	}

	result.vasrlr, err = client.ListByDatabaseResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "ListByDatabase", resp, "Failure responding to request")
		return
	}
	if result.vasrlr.hasNextLink() && result.vasrlr.IsEmpty() {
		err = result.NextWithContext(ctx)
		return
	}

	return
}

// ListByDatabasePreparer prepares the ListByDatabase request.
func (client DatabaseVulnerabilityAssessmentScansClient) ListByDatabasePreparer(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"databaseName":                autorest.Encode("path", databaseName),
		"resourceGroupName":           autorest.Encode("path", resourceGroupName),
		"serverName":                  autorest.Encode("path", serverName),
		"subscriptionId":              autorest.Encode("path", client.SubscriptionID),
		"vulnerabilityAssessmentName": autorest.Encode("path", "default"),
	}

	const APIVersion = "2017-10-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/servers/{serverName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

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

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

// listByDatabaseNextResults retrieves the next set of results, if any.
func (client DatabaseVulnerabilityAssessmentScansClient) listByDatabaseNextResults(ctx context.Context, lastResults VulnerabilityAssessmentScanRecordListResult) (result VulnerabilityAssessmentScanRecordListResult, err error) {
	req, err := lastResults.vulnerabilityAssessmentScanRecordListResultPreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "listByDatabaseNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListByDatabaseSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "listByDatabaseNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListByDatabaseResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansClient", "listByDatabaseNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListByDatabaseComplete enumerates all values, automatically crossing page boundaries as required.
func (client DatabaseVulnerabilityAssessmentScansClient) ListByDatabaseComplete(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (result VulnerabilityAssessmentScanRecordListResultIterator, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/DatabaseVulnerabilityAssessmentScansClient.ListByDatabase")
		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.ListByDatabase(ctx, resourceGroupName, serverName, databaseName)
	return
}
