package keyvault

// 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/autorest/validation"
	"github.com/Azure/go-autorest/tracing"
	"net/http"
)

// KeysClient is the the Azure management API provides a RESTful set of web services that interact with Azure Key
// Vault.
type KeysClient struct {
	BaseClient
}

// NewKeysClient creates an instance of the KeysClient client.
func NewKeysClient(subscriptionID string) KeysClient {
	return NewKeysClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

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

// CreateIfNotExist creates the first version of a new key if it does not exist. If it already exists, then the
// existing key is returned without any write operations being performed. This API does not create subsequent versions,
// and does not update existing keys.
// Parameters:
// resourceGroupName - the name of the resource group which contains the specified key vault.
// vaultName - the name of the key vault which contains the key to be created.
// keyName - the name of the key to be created.
// parameters - the parameters used to create the specified key.
func (client KeysClient) CreateIfNotExist(ctx context.Context, resourceGroupName string, vaultName string, keyName string, parameters KeyCreateParameters) (result Key, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/KeysClient.CreateIfNotExist")
		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: vaultName,
			Constraints: []validation.Constraint{{Target: "vaultName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9-]{3,24}$`, Chain: nil}}},
		{TargetValue: keyName,
			Constraints: []validation.Constraint{{Target: "keyName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9-]{1,127}$`, Chain: nil}}},
		{TargetValue: parameters,
			Constraints: []validation.Constraint{{Target: "parameters.Properties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
		return result, validation.NewError("keyvault.KeysClient", "CreateIfNotExist", err.Error())
	}

	req, err := client.CreateIfNotExistPreparer(ctx, resourceGroupName, vaultName, keyName, parameters)
	if err != nil {
		err = autorest.NewErrorWithError(err, "keyvault.KeysClient", "CreateIfNotExist", nil, "Failure preparing request")
		return
	}

	resp, err := client.CreateIfNotExistSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "keyvault.KeysClient", "CreateIfNotExist", resp, "Failure sending request")
		return
	}

	result, err = client.CreateIfNotExistResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "keyvault.KeysClient", "CreateIfNotExist", resp, "Failure responding to request")
		return
	}

	return
}

// CreateIfNotExistPreparer prepares the CreateIfNotExist request.
func (client KeysClient) CreateIfNotExistPreparer(ctx context.Context, resourceGroupName string, vaultName string, keyName string, parameters KeyCreateParameters) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"keyName":           autorest.Encode("path", keyName),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
		"vaultName":         autorest.Encode("path", vaultName),
	}

	const APIVersion = "2019-09-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/json; charset=utf-8"),
		autorest.AsPut(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}", pathParameters),
		autorest.WithJSON(parameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

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

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

// Get gets the current version of the specified key from the specified key vault.
// Parameters:
// resourceGroupName - the name of the resource group which contains the specified key vault.
// vaultName - the name of the vault which contains the key to be retrieved.
// keyName - the name of the key to be retrieved.
func (client KeysClient) Get(ctx context.Context, resourceGroupName string, vaultName string, keyName string) (result Key, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/KeysClient.Get")
		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: vaultName,
			Constraints: []validation.Constraint{{Target: "vaultName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9-]{3,24}$`, Chain: nil}}},
		{TargetValue: keyName,
			Constraints: []validation.Constraint{{Target: "keyName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9-]{1,127}$`, Chain: nil}}}}); err != nil {
		return result, validation.NewError("keyvault.KeysClient", "Get", err.Error())
	}

	req, err := client.GetPreparer(ctx, resourceGroupName, vaultName, keyName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "keyvault.KeysClient", "Get", nil, "Failure preparing request")
		return
	}

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

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

	return
}

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

	const APIVersion = "2019-09-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}", 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 KeysClient) 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 KeysClient) GetResponder(resp *http.Response) (result Key, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// GetVersion gets the specified version of the specified key in the specified key vault.
// Parameters:
// resourceGroupName - the name of the resource group which contains the specified key vault.
// vaultName - the name of the vault which contains the key version to be retrieved.
// keyName - the name of the key version to be retrieved.
// keyVersion - the version of the key to be retrieved.
func (client KeysClient) GetVersion(ctx context.Context, resourceGroupName string, vaultName string, keyName string, keyVersion string) (result Key, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/KeysClient.GetVersion")
		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: vaultName,
			Constraints: []validation.Constraint{{Target: "vaultName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9-]{3,24}$`, Chain: nil}}},
		{TargetValue: keyName,
			Constraints: []validation.Constraint{{Target: "keyName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9-]{1,127}$`, Chain: nil}}},
		{TargetValue: keyVersion,
			Constraints: []validation.Constraint{{Target: "keyVersion", Name: validation.Pattern, Rule: `^[a-fA-F0-9]{32}$`, Chain: nil}}}}); err != nil {
		return result, validation.NewError("keyvault.KeysClient", "GetVersion", err.Error())
	}

	req, err := client.GetVersionPreparer(ctx, resourceGroupName, vaultName, keyName, keyVersion)
	if err != nil {
		err = autorest.NewErrorWithError(err, "keyvault.KeysClient", "GetVersion", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetVersionSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "keyvault.KeysClient", "GetVersion", resp, "Failure sending request")
		return
	}

	result, err = client.GetVersionResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "keyvault.KeysClient", "GetVersion", resp, "Failure responding to request")
		return
	}

	return
}

// GetVersionPreparer prepares the GetVersion request.
func (client KeysClient) GetVersionPreparer(ctx context.Context, resourceGroupName string, vaultName string, keyName string, keyVersion string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"keyName":           autorest.Encode("path", keyName),
		"keyVersion":        autorest.Encode("path", keyVersion),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
		"vaultName":         autorest.Encode("path", vaultName),
	}

	const APIVersion = "2019-09-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}/versions/{keyVersion}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

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

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

// List lists the keys in the specified key vault.
// Parameters:
// resourceGroupName - the name of the resource group which contains the specified key vault.
// vaultName - the name of the vault which contains the keys to be retrieved.
func (client KeysClient) List(ctx context.Context, resourceGroupName string, vaultName string) (result KeyListResultPage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/KeysClient.List")
		defer func() {
			sc := -1
			if result.klr.Response.Response != nil {
				sc = result.klr.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	if err := validation.Validate([]validation.Validation{
		{TargetValue: vaultName,
			Constraints: []validation.Constraint{{Target: "vaultName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9-]{3,24}$`, Chain: nil}}}}); err != nil {
		return result, validation.NewError("keyvault.KeysClient", "List", err.Error())
	}

	result.fn = client.listNextResults
	req, err := client.ListPreparer(ctx, resourceGroupName, vaultName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "keyvault.KeysClient", "List", nil, "Failure preparing request")
		return
	}

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

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

	return
}

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

	const APIVersion = "2019-09-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys", 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 KeysClient) 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 KeysClient) ListResponder(resp *http.Response) (result KeyListResult, 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 KeysClient) listNextResults(ctx context.Context, lastResults KeyListResult) (result KeyListResult, err error) {
	req, err := lastResults.keyListResultPreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "keyvault.KeysClient", "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, "keyvault.KeysClient", "listNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "keyvault.KeysClient", "listNextResults", resp, "Failure responding to next results request")
	}
	return
}

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

// ListVersions lists the versions of the specified key in the specified key vault.
// Parameters:
// resourceGroupName - the name of the resource group which contains the specified key vault.
// vaultName - the name of the vault which contains the key versions to be retrieved.
// keyName - the name of the key versions to be retrieved.
func (client KeysClient) ListVersions(ctx context.Context, resourceGroupName string, vaultName string, keyName string) (result KeyListResultPage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/KeysClient.ListVersions")
		defer func() {
			sc := -1
			if result.klr.Response.Response != nil {
				sc = result.klr.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	if err := validation.Validate([]validation.Validation{
		{TargetValue: vaultName,
			Constraints: []validation.Constraint{{Target: "vaultName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9-]{3,24}$`, Chain: nil}}},
		{TargetValue: keyName,
			Constraints: []validation.Constraint{{Target: "keyName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9-]{1,127}$`, Chain: nil}}}}); err != nil {
		return result, validation.NewError("keyvault.KeysClient", "ListVersions", err.Error())
	}

	result.fn = client.listVersionsNextResults
	req, err := client.ListVersionsPreparer(ctx, resourceGroupName, vaultName, keyName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "keyvault.KeysClient", "ListVersions", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListVersionsSender(req)
	if err != nil {
		result.klr.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "keyvault.KeysClient", "ListVersions", resp, "Failure sending request")
		return
	}

	result.klr, err = client.ListVersionsResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "keyvault.KeysClient", "ListVersions", resp, "Failure responding to request")
		return
	}
	if result.klr.hasNextLink() && result.klr.IsEmpty() {
		err = result.NextWithContext(ctx)
		return
	}

	return
}

// ListVersionsPreparer prepares the ListVersions request.
func (client KeysClient) ListVersionsPreparer(ctx context.Context, resourceGroupName string, vaultName string, keyName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"keyName":           autorest.Encode("path", keyName),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
		"vaultName":         autorest.Encode("path", vaultName),
	}

	const APIVersion = "2019-09-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

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

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

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

// listVersionsNextResults retrieves the next set of results, if any.
func (client KeysClient) listVersionsNextResults(ctx context.Context, lastResults KeyListResult) (result KeyListResult, err error) {
	req, err := lastResults.keyListResultPreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "keyvault.KeysClient", "listVersionsNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListVersionsSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "keyvault.KeysClient", "listVersionsNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListVersionsResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "keyvault.KeysClient", "listVersionsNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListVersionsComplete enumerates all values, automatically crossing page boundaries as required.
func (client KeysClient) ListVersionsComplete(ctx context.Context, resourceGroupName string, vaultName string, keyName string) (result KeyListResultIterator, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/KeysClient.ListVersions")
		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.ListVersions(ctx, resourceGroupName, vaultName, keyName)
	return
}
