// 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. DO NOT EDIT.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

package fake

import (
	"context"
	"errors"
	"fmt"
	azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/v2"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
)

// LocalUsersServer is a fake server for instances of the armstorage.LocalUsersClient type.
type LocalUsersServer struct {
	// CreateOrUpdate is the fake for method LocalUsersClient.CreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK
	CreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, username string, properties armstorage.LocalUser, options *armstorage.LocalUsersClientCreateOrUpdateOptions) (resp azfake.Responder[armstorage.LocalUsersClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// Delete is the fake for method LocalUsersClient.Delete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent
	Delete func(ctx context.Context, resourceGroupName string, accountName string, username string, options *armstorage.LocalUsersClientDeleteOptions) (resp azfake.Responder[armstorage.LocalUsersClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method LocalUsersClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, accountName string, username string, options *armstorage.LocalUsersClientGetOptions) (resp azfake.Responder[armstorage.LocalUsersClientGetResponse], errResp azfake.ErrorResponder)

	// NewListPager is the fake for method LocalUsersClient.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(resourceGroupName string, accountName string, options *armstorage.LocalUsersClientListOptions) (resp azfake.PagerResponder[armstorage.LocalUsersClientListResponse])

	// ListKeys is the fake for method LocalUsersClient.ListKeys
	// HTTP status codes to indicate success: http.StatusOK
	ListKeys func(ctx context.Context, resourceGroupName string, accountName string, username string, options *armstorage.LocalUsersClientListKeysOptions) (resp azfake.Responder[armstorage.LocalUsersClientListKeysResponse], errResp azfake.ErrorResponder)

	// RegeneratePassword is the fake for method LocalUsersClient.RegeneratePassword
	// HTTP status codes to indicate success: http.StatusOK
	RegeneratePassword func(ctx context.Context, resourceGroupName string, accountName string, username string, options *armstorage.LocalUsersClientRegeneratePasswordOptions) (resp azfake.Responder[armstorage.LocalUsersClientRegeneratePasswordResponse], errResp azfake.ErrorResponder)
}

// NewLocalUsersServerTransport creates a new instance of LocalUsersServerTransport with the provided implementation.
// The returned LocalUsersServerTransport instance is connected to an instance of armstorage.LocalUsersClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewLocalUsersServerTransport(srv *LocalUsersServer) *LocalUsersServerTransport {
	return &LocalUsersServerTransport{
		srv:          srv,
		newListPager: newTracker[azfake.PagerResponder[armstorage.LocalUsersClientListResponse]](),
	}
}

// LocalUsersServerTransport connects instances of armstorage.LocalUsersClient to instances of LocalUsersServer.
// Don't use this type directly, use NewLocalUsersServerTransport instead.
type LocalUsersServerTransport struct {
	srv          *LocalUsersServer
	newListPager *tracker[azfake.PagerResponder[armstorage.LocalUsersClientListResponse]]
}

// Do implements the policy.Transporter interface for LocalUsersServerTransport.
func (l *LocalUsersServerTransport) Do(req *http.Request) (*http.Response, error) {
	rawMethod := req.Context().Value(runtime.CtxAPINameKey{})
	method, ok := rawMethod.(string)
	if !ok {
		return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")}
	}

	return l.dispatchToMethodFake(req, method)
}

func (l *LocalUsersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) {
	resultChan := make(chan result)
	defer close(resultChan)

	go func() {
		var intercepted bool
		var res result
		if localUsersServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = localUsersServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "LocalUsersClient.CreateOrUpdate":
				res.resp, res.err = l.dispatchCreateOrUpdate(req)
			case "LocalUsersClient.Delete":
				res.resp, res.err = l.dispatchDelete(req)
			case "LocalUsersClient.Get":
				res.resp, res.err = l.dispatchGet(req)
			case "LocalUsersClient.NewListPager":
				res.resp, res.err = l.dispatchNewListPager(req)
			case "LocalUsersClient.ListKeys":
				res.resp, res.err = l.dispatchListKeys(req)
			case "LocalUsersClient.RegeneratePassword":
				res.resp, res.err = l.dispatchRegeneratePassword(req)
			default:
				res.err = fmt.Errorf("unhandled API %s", method)
			}

		}
		select {
		case resultChan <- res:
		case <-req.Context().Done():
		}
	}()

	select {
	case <-req.Context().Done():
		return nil, req.Context().Err()
	case res := <-resultChan:
		return res.resp, res.err
	}
}

func (l *LocalUsersServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if l.srv.CreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Storage/storageAccounts/(?P<accountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/localUsers/(?P<username>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 5 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armstorage.LocalUser](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")])
	if err != nil {
		return nil, err
	}
	usernameParam, err := url.PathUnescape(matches[regex.SubexpIndex("username")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := l.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, usernameParam, body, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)}
	}
	resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).LocalUser, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (l *LocalUsersServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) {
	if l.srv.Delete == nil {
		return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Storage/storageAccounts/(?P<accountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/localUsers/(?P<username>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 5 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")])
	if err != nil {
		return nil, err
	}
	usernameParam, err := url.PathUnescape(matches[regex.SubexpIndex("username")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := l.srv.Delete(req.Context(), resourceGroupNameParam, accountNameParam, usernameParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)}
	}
	resp, err := server.NewResponse(respContent, req, nil)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (l *LocalUsersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if l.srv.Get == nil {
		return nil, &nonRetriableError{errors.New("fake for method Get not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Storage/storageAccounts/(?P<accountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/localUsers/(?P<username>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 5 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")])
	if err != nil {
		return nil, err
	}
	usernameParam, err := url.PathUnescape(matches[regex.SubexpIndex("username")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := l.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, usernameParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)}
	}
	resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).LocalUser, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (l *LocalUsersServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) {
	if l.srv.NewListPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")}
	}
	newListPager := l.newListPager.get(req)
	if newListPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Storage/storageAccounts/(?P<accountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/localUsers`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if len(matches) < 4 {
			return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
		}
		qp := req.URL.Query()
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")])
		if err != nil {
			return nil, err
		}
		maxpagesizeUnescaped, err := url.QueryUnescape(qp.Get("$maxpagesize"))
		if err != nil {
			return nil, err
		}
		maxpagesizeParam, err := parseOptional(maxpagesizeUnescaped, func(v string) (int32, error) {
			p, parseErr := strconv.ParseInt(v, 10, 32)
			if parseErr != nil {
				return 0, parseErr
			}
			return int32(p), nil
		})
		if err != nil {
			return nil, err
		}
		filterUnescaped, err := url.QueryUnescape(qp.Get("$filter"))
		if err != nil {
			return nil, err
		}
		filterParam := getOptional(filterUnescaped)
		includeUnescaped, err := url.QueryUnescape(qp.Get("$include"))
		if err != nil {
			return nil, err
		}
		includeParam := getOptional(armstorage.ListLocalUserIncludeParam(includeUnescaped))
		var options *armstorage.LocalUsersClientListOptions
		if maxpagesizeParam != nil || filterParam != nil || includeParam != nil {
			options = &armstorage.LocalUsersClientListOptions{
				Maxpagesize: maxpagesizeParam,
				Filter:      filterParam,
				Include:     includeParam,
			}
		}
		resp := l.srv.NewListPager(resourceGroupNameParam, accountNameParam, options)
		newListPager = &resp
		l.newListPager.add(req, newListPager)
	}
	resp, err := server.PagerResponderNext(newListPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		l.newListPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListPager) {
		l.newListPager.remove(req)
	}
	return resp, nil
}

func (l *LocalUsersServerTransport) dispatchListKeys(req *http.Request) (*http.Response, error) {
	if l.srv.ListKeys == nil {
		return nil, &nonRetriableError{errors.New("fake for method ListKeys not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Storage/storageAccounts/(?P<accountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/localUsers/(?P<username>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/listKeys`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 5 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")])
	if err != nil {
		return nil, err
	}
	usernameParam, err := url.PathUnescape(matches[regex.SubexpIndex("username")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := l.srv.ListKeys(req.Context(), resourceGroupNameParam, accountNameParam, usernameParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)}
	}
	resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).LocalUserKeys, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (l *LocalUsersServerTransport) dispatchRegeneratePassword(req *http.Request) (*http.Response, error) {
	if l.srv.RegeneratePassword == nil {
		return nil, &nonRetriableError{errors.New("fake for method RegeneratePassword not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Storage/storageAccounts/(?P<accountName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/localUsers/(?P<username>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/regeneratePassword`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 5 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")])
	if err != nil {
		return nil, err
	}
	usernameParam, err := url.PathUnescape(matches[regex.SubexpIndex("username")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := l.srv.RegeneratePassword(req.Context(), resourceGroupNameParam, accountNameParam, usernameParam, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)}
	}
	resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).LocalUserRegeneratePasswordResult, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

// set this to conditionally intercept incoming requests to LocalUsersServerTransport
var localUsersServerTransportInterceptor interface {
	// Do returns true if the server transport should use the returned response/error
	Do(*http.Request) (*http.Response, error, bool)
}
