package synapse

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

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

// LibraryClient is the client for the Library methods of the Synapse service.
type LibraryClient struct {
	BaseClient
}

// NewLibraryClient creates an instance of the LibraryClient client.
func NewLibraryClient(endpoint string) LibraryClient {
	return LibraryClient{New(endpoint)}
}

// Append append the content to the library resource created using the create operation. The maximum content size is
// 4MiB. Content larger than 4MiB must be appended in 4MiB chunks
// Parameters:
// libraryName - file name to upload. Minimum length of the filename should be 1 excluding the extension
// length.
// content - library file chunk.
// blobConditionAppendPosition - set this header to a byte offset at which the block is expected to be
// appended. The request succeeds only if the current offset matches this value. Otherwise, the request fails
// with the AppendPositionConditionNotMet error (HTTP status code 412 â€“ Precondition Failed)
func (client LibraryClient) Append(ctx context.Context, libraryName string, content string, blobConditionAppendPosition *int64) (result autorest.Response, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/LibraryClient.Append")
		defer func() {
			sc := -1
			if result.Response != nil {
				sc = result.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	if err := validation.Validate([]validation.Validation{
		{TargetValue: libraryName,
			Constraints: []validation.Constraint{{Target: "libraryName", Name: validation.MaxLength, Rule: 100, Chain: nil}}}}); err != nil {
		return result, validation.NewError("synapse.LibraryClient", "Append", err.Error())
	}

	req, err := client.AppendPreparer(ctx, libraryName, content, blobConditionAppendPosition)
	if err != nil {
		err = autorest.NewErrorWithError(err, "synapse.LibraryClient", "Append", nil, "Failure preparing request")
		return
	}

	resp, err := client.AppendSender(req)
	if err != nil {
		result.Response = resp
		err = autorest.NewErrorWithError(err, "synapse.LibraryClient", "Append", resp, "Failure sending request")
		return
	}

	result, err = client.AppendResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "synapse.LibraryClient", "Append", resp, "Failure responding to request")
		return
	}

	return
}

// AppendPreparer prepares the Append request.
func (client LibraryClient) AppendPreparer(ctx context.Context, libraryName string, content string, blobConditionAppendPosition *int64) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"endpoint": client.Endpoint,
	}

	pathParameters := map[string]interface{}{
		"libraryName": autorest.Encode("path", libraryName),
	}

	const APIVersion = "2021-06-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
		"comp":        autorest.Encode("query", "appendblock"),
	}

	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/octet-stream"),
		autorest.AsPut(),
		autorest.WithCustomBaseURL("{endpoint}", urlParameters),
		autorest.WithPathParameters("/libraries/{libraryName}", pathParameters),
		autorest.WithJSON(content),
		autorest.WithQueryParameters(queryParameters))
	if blobConditionAppendPosition != nil {
		preparer = autorest.DecoratePreparer(preparer,
			autorest.WithHeader("x-ms-blob-condition-appendpos", autorest.String(*blobConditionAppendPosition)))
	}
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

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

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

// Create creates a library with the library name.
// Parameters:
// libraryName - file name to upload. Minimum length of the filename should be 1 excluding the extension
// length.
func (client LibraryClient) Create(ctx context.Context, libraryName string) (result LibraryCreateFuture, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/LibraryClient.Create")
		defer func() {
			sc := -1
			if result.FutureAPI != nil && result.FutureAPI.Response() != nil {
				sc = result.FutureAPI.Response().StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	if err := validation.Validate([]validation.Validation{
		{TargetValue: libraryName,
			Constraints: []validation.Constraint{{Target: "libraryName", Name: validation.MaxLength, Rule: 100, Chain: nil}}}}); err != nil {
		return result, validation.NewError("synapse.LibraryClient", "Create", err.Error())
	}

	req, err := client.CreatePreparer(ctx, libraryName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "synapse.LibraryClient", "Create", nil, "Failure preparing request")
		return
	}

	result, err = client.CreateSender(req)
	if err != nil {
		err = autorest.NewErrorWithError(err, "synapse.LibraryClient", "Create", result.Response(), "Failure sending request")
		return
	}

	return
}

// CreatePreparer prepares the Create request.
func (client LibraryClient) CreatePreparer(ctx context.Context, libraryName string) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"endpoint": client.Endpoint,
	}

	pathParameters := map[string]interface{}{
		"libraryName": autorest.Encode("path", libraryName),
	}

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

	preparer := autorest.CreatePreparer(
		autorest.AsPut(),
		autorest.WithCustomBaseURL("{endpoint}", urlParameters),
		autorest.WithPathParameters("/libraries/{libraryName}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client LibraryClient) CreateSender(req *http.Request) (future LibraryCreateFuture, err error) {
	var resp *http.Response
	future.FutureAPI = &azure.Future{}
	resp, err = client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	if err != nil {
		return
	}
	var azf azure.Future
	azf, err = azure.NewFutureFromResponse(resp)
	future.FutureAPI = &azf
	future.Result = future.result
	return
}

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

// Delete delete Library
// Parameters:
// libraryName - file name to upload. Minimum length of the filename should be 1 excluding the extension
// length.
func (client LibraryClient) Delete(ctx context.Context, libraryName string) (result LibraryDeleteFuture, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/LibraryClient.Delete")
		defer func() {
			sc := -1
			if result.FutureAPI != nil && result.FutureAPI.Response() != nil {
				sc = result.FutureAPI.Response().StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	if err := validation.Validate([]validation.Validation{
		{TargetValue: libraryName,
			Constraints: []validation.Constraint{{Target: "libraryName", Name: validation.MaxLength, Rule: 100, Chain: nil}}}}); err != nil {
		return result, validation.NewError("synapse.LibraryClient", "Delete", err.Error())
	}

	req, err := client.DeletePreparer(ctx, libraryName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "synapse.LibraryClient", "Delete", nil, "Failure preparing request")
		return
	}

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

	return
}

// DeletePreparer prepares the Delete request.
func (client LibraryClient) DeletePreparer(ctx context.Context, libraryName string) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"endpoint": client.Endpoint,
	}

	pathParameters := map[string]interface{}{
		"libraryName": autorest.Encode("path", libraryName),
	}

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

	preparer := autorest.CreatePreparer(
		autorest.AsDelete(),
		autorest.WithCustomBaseURL("{endpoint}", urlParameters),
		autorest.WithPathParameters("/libraries/{libraryName}", 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 LibraryClient) DeleteSender(req *http.Request) (future LibraryDeleteFuture, err error) {
	var resp *http.Response
	future.FutureAPI = &azure.Future{}
	resp, err = client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	if err != nil {
		return
	}
	var azf azure.Future
	azf, err = azure.NewFutureFromResponse(resp)
	future.FutureAPI = &azf
	future.Result = future.result
	return
}

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

// Flush flush Library
// Parameters:
// libraryName - file name to upload. Minimum length of the filename should be 1 excluding the extension
// length.
func (client LibraryClient) Flush(ctx context.Context, libraryName string) (result LibraryFlushFuture, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/LibraryClient.Flush")
		defer func() {
			sc := -1
			if result.FutureAPI != nil && result.FutureAPI.Response() != nil {
				sc = result.FutureAPI.Response().StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	if err := validation.Validate([]validation.Validation{
		{TargetValue: libraryName,
			Constraints: []validation.Constraint{{Target: "libraryName", Name: validation.MaxLength, Rule: 100, Chain: nil}}}}); err != nil {
		return result, validation.NewError("synapse.LibraryClient", "Flush", err.Error())
	}

	req, err := client.FlushPreparer(ctx, libraryName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "synapse.LibraryClient", "Flush", nil, "Failure preparing request")
		return
	}

	result, err = client.FlushSender(req)
	if err != nil {
		err = autorest.NewErrorWithError(err, "synapse.LibraryClient", "Flush", result.Response(), "Failure sending request")
		return
	}

	return
}

// FlushPreparer prepares the Flush request.
func (client LibraryClient) FlushPreparer(ctx context.Context, libraryName string) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"endpoint": client.Endpoint,
	}

	pathParameters := map[string]interface{}{
		"libraryName": autorest.Encode("path", libraryName),
	}

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

	preparer := autorest.CreatePreparer(
		autorest.AsPost(),
		autorest.WithCustomBaseURL("{endpoint}", urlParameters),
		autorest.WithPathParameters("/libraries/{libraryName}/flush", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// FlushSender sends the Flush request. The method will close the
// http.Response Body if it receives an error.
func (client LibraryClient) FlushSender(req *http.Request) (future LibraryFlushFuture, err error) {
	var resp *http.Response
	future.FutureAPI = &azure.Future{}
	resp, err = client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	if err != nil {
		return
	}
	var azf azure.Future
	azf, err = azure.NewFutureFromResponse(resp)
	future.FutureAPI = &azf
	future.Result = future.result
	return
}

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

// Get get Library
// Parameters:
// libraryName - file name to upload. Minimum length of the filename should be 1 excluding the extension
// length.
func (client LibraryClient) Get(ctx context.Context, libraryName string) (result LibraryResource, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/LibraryClient.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: libraryName,
			Constraints: []validation.Constraint{{Target: "libraryName", Name: validation.MaxLength, Rule: 100, Chain: nil}}}}); err != nil {
		return result, validation.NewError("synapse.LibraryClient", "Get", err.Error())
	}

	req, err := client.GetPreparer(ctx, libraryName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "synapse.LibraryClient", "Get", nil, "Failure preparing request")
		return
	}

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

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

	return
}

// GetPreparer prepares the Get request.
func (client LibraryClient) GetPreparer(ctx context.Context, libraryName string) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"endpoint": client.Endpoint,
	}

	pathParameters := map[string]interface{}{
		"libraryName": autorest.Encode("path", libraryName),
	}

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

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithCustomBaseURL("{endpoint}", urlParameters),
		autorest.WithPathParameters("/libraries/{libraryName}", 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 LibraryClient) 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 LibraryClient) GetResponder(resp *http.Response) (result LibraryResource, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNotModified),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// GetOperationResult get Operation result for Library
// Parameters:
// operationID - operation id for which status is requested
func (client LibraryClient) GetOperationResult(ctx context.Context, operationID string) (result SetObject, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/LibraryClient.GetOperationResult")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.GetOperationResultPreparer(ctx, operationID)
	if err != nil {
		err = autorest.NewErrorWithError(err, "synapse.LibraryClient", "GetOperationResult", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetOperationResultSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "synapse.LibraryClient", "GetOperationResult", resp, "Failure sending request")
		return
	}

	result, err = client.GetOperationResultResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "synapse.LibraryClient", "GetOperationResult", resp, "Failure responding to request")
		return
	}

	return
}

// GetOperationResultPreparer prepares the GetOperationResult request.
func (client LibraryClient) GetOperationResultPreparer(ctx context.Context, operationID string) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"endpoint": client.Endpoint,
	}

	pathParameters := map[string]interface{}{
		"operationId": autorest.Encode("path", operationID),
	}

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

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithCustomBaseURL("{endpoint}", urlParameters),
		autorest.WithPathParameters("/libraryOperationResults/{operationId}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

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

// GetOperationResultResponder handles the response to the GetOperationResult request. The method always
// closes the http.Response Body.
func (client LibraryClient) GetOperationResultResponder(resp *http.Response) (result SetObject, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
		autorest.ByUnmarshallingJSON(&result.Value),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// List lists Library.
func (client LibraryClient) List(ctx context.Context) (result LibraryListResponsePage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/LibraryClient.List")
		defer func() {
			sc := -1
			if result.llr.Response.Response != nil {
				sc = result.llr.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.fn = client.listNextResults
	req, err := client.ListPreparer(ctx)
	if err != nil {
		err = autorest.NewErrorWithError(err, "synapse.LibraryClient", "List", nil, "Failure preparing request")
		return
	}

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

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

	return
}

// ListPreparer prepares the List request.
func (client LibraryClient) ListPreparer(ctx context.Context) (*http.Request, error) {
	urlParameters := map[string]interface{}{
		"endpoint": client.Endpoint,
	}

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

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithCustomBaseURL("{endpoint}", urlParameters),
		autorest.WithPath("/libraries"),
		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 LibraryClient) ListSender(req *http.Request) (*http.Response, error) {
	return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client LibraryClient) ListResponder(resp *http.Response) (result LibraryListResponse, 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 LibraryClient) listNextResults(ctx context.Context, lastResults LibraryListResponse) (result LibraryListResponse, err error) {
	req, err := lastResults.libraryListResponsePreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "synapse.LibraryClient", "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, "synapse.LibraryClient", "listNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "synapse.LibraryClient", "listNextResults", resp, "Failure responding to next results request")
	}
	return
}

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