// 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/azcore/to"
	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/integrationspaces/armintegrationspaces"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
)

// ApplicationResourcesServer is a fake server for instances of the armintegrationspaces.ApplicationResourcesClient type.
type ApplicationResourcesServer struct {
	// CreateOrUpdate is the fake for method ApplicationResourcesClient.CreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	CreateOrUpdate func(ctx context.Context, resourceGroupName string, spaceName string, applicationName string, resourceName string, resource armintegrationspaces.ApplicationResource, options *armintegrationspaces.ApplicationResourcesClientCreateOrUpdateOptions) (resp azfake.Responder[armintegrationspaces.ApplicationResourcesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// Delete is the fake for method ApplicationResourcesClient.Delete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent
	Delete func(ctx context.Context, resourceGroupName string, spaceName string, applicationName string, resourceName string, options *armintegrationspaces.ApplicationResourcesClientDeleteOptions) (resp azfake.Responder[armintegrationspaces.ApplicationResourcesClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method ApplicationResourcesClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, spaceName string, applicationName string, resourceName string, options *armintegrationspaces.ApplicationResourcesClientGetOptions) (resp azfake.Responder[armintegrationspaces.ApplicationResourcesClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByApplicationPager is the fake for method ApplicationResourcesClient.NewListByApplicationPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByApplicationPager func(resourceGroupName string, spaceName string, applicationName string, options *armintegrationspaces.ApplicationResourcesClientListByApplicationOptions) (resp azfake.PagerResponder[armintegrationspaces.ApplicationResourcesClientListByApplicationResponse])

	// Patch is the fake for method ApplicationResourcesClient.Patch
	// HTTP status codes to indicate success: http.StatusOK
	Patch func(ctx context.Context, resourceGroupName string, spaceName string, applicationName string, resourceName string, properties armintegrationspaces.ApplicationResourceUpdate, options *armintegrationspaces.ApplicationResourcesClientPatchOptions) (resp azfake.Responder[armintegrationspaces.ApplicationResourcesClientPatchResponse], errResp azfake.ErrorResponder)
}

// NewApplicationResourcesServerTransport creates a new instance of ApplicationResourcesServerTransport with the provided implementation.
// The returned ApplicationResourcesServerTransport instance is connected to an instance of armintegrationspaces.ApplicationResourcesClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewApplicationResourcesServerTransport(srv *ApplicationResourcesServer) *ApplicationResourcesServerTransport {
	return &ApplicationResourcesServerTransport{
		srv:                       srv,
		newListByApplicationPager: newTracker[azfake.PagerResponder[armintegrationspaces.ApplicationResourcesClientListByApplicationResponse]](),
	}
}

// ApplicationResourcesServerTransport connects instances of armintegrationspaces.ApplicationResourcesClient to instances of ApplicationResourcesServer.
// Don't use this type directly, use NewApplicationResourcesServerTransport instead.
type ApplicationResourcesServerTransport struct {
	srv                       *ApplicationResourcesServer
	newListByApplicationPager *tracker[azfake.PagerResponder[armintegrationspaces.ApplicationResourcesClientListByApplicationResponse]]
}

// Do implements the policy.Transporter interface for ApplicationResourcesServerTransport.
func (a *ApplicationResourcesServerTransport) 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")}
	}

	var resp *http.Response
	var err error

	switch method {
	case "ApplicationResourcesClient.CreateOrUpdate":
		resp, err = a.dispatchCreateOrUpdate(req)
	case "ApplicationResourcesClient.Delete":
		resp, err = a.dispatchDelete(req)
	case "ApplicationResourcesClient.Get":
		resp, err = a.dispatchGet(req)
	case "ApplicationResourcesClient.NewListByApplicationPager":
		resp, err = a.dispatchNewListByApplicationPager(req)
	case "ApplicationResourcesClient.Patch":
		resp, err = a.dispatchPatch(req)
	default:
		err = fmt.Errorf("unhandled API %s", method)
	}

	if err != nil {
		return nil, err
	}

	return resp, nil
}

func (a *ApplicationResourcesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if a.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\.IntegrationSpaces/spaces/(?P<spaceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P<applicationName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resources/(?P<resourceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 5 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armintegrationspaces.ApplicationResource](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	spaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("spaceName")])
	if err != nil {
		return nil, err
	}
	applicationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("applicationName")])
	if err != nil {
		return nil, err
	}
	resourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := a.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, spaceNameParam, applicationNameParam, resourceNameParam, body, nil)
	if respErr := server.GetError(errRespr, req); respErr != nil {
		return nil, respErr
	}
	respContent := server.GetResponseContent(respr)
	if !contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) {
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)}
	}
	resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ApplicationResource, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (a *ApplicationResourcesServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) {
	if a.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\.IntegrationSpaces/spaces/(?P<spaceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P<applicationName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resources/(?P<resourceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || 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
	}
	spaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("spaceName")])
	if err != nil {
		return nil, err
	}
	applicationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("applicationName")])
	if err != nil {
		return nil, err
	}
	resourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := a.srv.Delete(req.Context(), resourceGroupNameParam, spaceNameParam, applicationNameParam, resourceNameParam, 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 (a *ApplicationResourcesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if a.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\.IntegrationSpaces/spaces/(?P<spaceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P<applicationName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resources/(?P<resourceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || 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
	}
	spaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("spaceName")])
	if err != nil {
		return nil, err
	}
	applicationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("applicationName")])
	if err != nil {
		return nil, err
	}
	resourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, spaceNameParam, applicationNameParam, resourceNameParam, 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).ApplicationResource, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (a *ApplicationResourcesServerTransport) dispatchNewListByApplicationPager(req *http.Request) (*http.Response, error) {
	if a.srv.NewListByApplicationPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByApplicationPager not implemented")}
	}
	newListByApplicationPager := a.newListByApplicationPager.get(req)
	if newListByApplicationPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.IntegrationSpaces/spaces/(?P<spaceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P<applicationName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resources`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if matches == nil || 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
		}
		topUnescaped, err := url.QueryUnescape(qp.Get("top"))
		if err != nil {
			return nil, err
		}
		topParam, err := parseOptional(topUnescaped, 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
		}
		skipUnescaped, err := url.QueryUnescape(qp.Get("skip"))
		if err != nil {
			return nil, err
		}
		skipParam, err := parseOptional(skipUnescaped, 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
		}
		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)
		selectEscaped := qp["select"]
		selectParam := make([]string, len(selectEscaped))
		for i, v := range selectEscaped {
			u, unescapeErr := url.QueryUnescape(v)
			if unescapeErr != nil {
				return nil, unescapeErr
			}
			selectParam[i] = u
		}
		expandEscaped := qp["expand"]
		expandParam := make([]string, len(expandEscaped))
		for i, v := range expandEscaped {
			u, unescapeErr := url.QueryUnescape(v)
			if unescapeErr != nil {
				return nil, unescapeErr
			}
			expandParam[i] = u
		}
		orderbyEscaped := qp["orderby"]
		orderbyParam := make([]string, len(orderbyEscaped))
		for i, v := range orderbyEscaped {
			u, unescapeErr := url.QueryUnescape(v)
			if unescapeErr != nil {
				return nil, unescapeErr
			}
			orderbyParam[i] = u
		}
		spaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("spaceName")])
		if err != nil {
			return nil, err
		}
		applicationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("applicationName")])
		if err != nil {
			return nil, err
		}
		var options *armintegrationspaces.ApplicationResourcesClientListByApplicationOptions
		if topParam != nil || skipParam != nil || maxpagesizeParam != nil || filterParam != nil || len(selectParam) > 0 || len(expandParam) > 0 || len(orderbyParam) > 0 {
			options = &armintegrationspaces.ApplicationResourcesClientListByApplicationOptions{
				Top:         topParam,
				Skip:        skipParam,
				Maxpagesize: maxpagesizeParam,
				Filter:      filterParam,
				Select:      selectParam,
				Expand:      expandParam,
				Orderby:     orderbyParam,
			}
		}
		resp := a.srv.NewListByApplicationPager(resourceGroupNameParam, spaceNameParam, applicationNameParam, options)
		newListByApplicationPager = &resp
		a.newListByApplicationPager.add(req, newListByApplicationPager)
		server.PagerResponderInjectNextLinks(newListByApplicationPager, req, func(page *armintegrationspaces.ApplicationResourcesClientListByApplicationResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByApplicationPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		a.newListByApplicationPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByApplicationPager) {
		a.newListByApplicationPager.remove(req)
	}
	return resp, nil
}

func (a *ApplicationResourcesServerTransport) dispatchPatch(req *http.Request) (*http.Response, error) {
	if a.srv.Patch == nil {
		return nil, &nonRetriableError{errors.New("fake for method Patch not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.IntegrationSpaces/spaces/(?P<spaceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P<applicationName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resources/(?P<resourceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 5 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armintegrationspaces.ApplicationResourceUpdate](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	spaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("spaceName")])
	if err != nil {
		return nil, err
	}
	applicationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("applicationName")])
	if err != nil {
		return nil, err
	}
	resourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := a.srv.Patch(req.Context(), resourceGroupNameParam, spaceNameParam, applicationNameParam, resourceNameParam, 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).ApplicationResource, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}
