// 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/applicationinsights/armapplicationinsights/v2"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
)

// FavoritesServer is a fake server for instances of the armapplicationinsights.FavoritesClient type.
type FavoritesServer struct {
	// Add is the fake for method FavoritesClient.Add
	// HTTP status codes to indicate success: http.StatusOK
	Add func(ctx context.Context, resourceGroupName string, resourceName string, favoriteID string, favoriteProperties armapplicationinsights.ComponentFavorite, options *armapplicationinsights.FavoritesClientAddOptions) (resp azfake.Responder[armapplicationinsights.FavoritesClientAddResponse], errResp azfake.ErrorResponder)

	// Delete is the fake for method FavoritesClient.Delete
	// HTTP status codes to indicate success: http.StatusOK
	Delete func(ctx context.Context, resourceGroupName string, resourceName string, favoriteID string, options *armapplicationinsights.FavoritesClientDeleteOptions) (resp azfake.Responder[armapplicationinsights.FavoritesClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method FavoritesClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, resourceName string, favoriteID string, options *armapplicationinsights.FavoritesClientGetOptions) (resp azfake.Responder[armapplicationinsights.FavoritesClientGetResponse], errResp azfake.ErrorResponder)

	// List is the fake for method FavoritesClient.List
	// HTTP status codes to indicate success: http.StatusOK
	List func(ctx context.Context, resourceGroupName string, resourceName string, options *armapplicationinsights.FavoritesClientListOptions) (resp azfake.Responder[armapplicationinsights.FavoritesClientListResponse], errResp azfake.ErrorResponder)

	// Update is the fake for method FavoritesClient.Update
	// HTTP status codes to indicate success: http.StatusOK
	Update func(ctx context.Context, resourceGroupName string, resourceName string, favoriteID string, favoriteProperties armapplicationinsights.ComponentFavorite, options *armapplicationinsights.FavoritesClientUpdateOptions) (resp azfake.Responder[armapplicationinsights.FavoritesClientUpdateResponse], errResp azfake.ErrorResponder)
}

// NewFavoritesServerTransport creates a new instance of FavoritesServerTransport with the provided implementation.
// The returned FavoritesServerTransport instance is connected to an instance of armapplicationinsights.FavoritesClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewFavoritesServerTransport(srv *FavoritesServer) *FavoritesServerTransport {
	return &FavoritesServerTransport{srv: srv}
}

// FavoritesServerTransport connects instances of armapplicationinsights.FavoritesClient to instances of FavoritesServer.
// Don't use this type directly, use NewFavoritesServerTransport instead.
type FavoritesServerTransport struct {
	srv *FavoritesServer
}

// Do implements the policy.Transporter interface for FavoritesServerTransport.
func (f *FavoritesServerTransport) 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 f.dispatchToMethodFake(req, method)
}

func (f *FavoritesServerTransport) 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 favoritesServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = favoritesServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "FavoritesClient.Add":
				res.resp, res.err = f.dispatchAdd(req)
			case "FavoritesClient.Delete":
				res.resp, res.err = f.dispatchDelete(req)
			case "FavoritesClient.Get":
				res.resp, res.err = f.dispatchGet(req)
			case "FavoritesClient.List":
				res.resp, res.err = f.dispatchList(req)
			case "FavoritesClient.Update":
				res.resp, res.err = f.dispatchUpdate(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 (f *FavoritesServerTransport) dispatchAdd(req *http.Request) (*http.Response, error) {
	if f.srv.Add == nil {
		return nil, &nonRetriableError{errors.New("fake for method Add not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Insights/components/(?P<resourceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/favorites/(?P<favoriteId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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)
	}
	body, err := server.UnmarshalRequestAsJSON[armapplicationinsights.ComponentFavorite](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	resourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceName")])
	if err != nil {
		return nil, err
	}
	favoriteIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("favoriteId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := f.srv.Add(req.Context(), resourceGroupNameParam, resourceNameParam, favoriteIDParam, 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).ComponentFavorite, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (f *FavoritesServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) {
	if f.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\.Insights/components/(?P<resourceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/favorites/(?P<favoriteId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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)
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	resourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceName")])
	if err != nil {
		return nil, err
	}
	favoriteIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("favoriteId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := f.srv.Delete(req.Context(), resourceGroupNameParam, resourceNameParam, favoriteIDParam, 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.NewResponse(respContent, req, nil)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (f *FavoritesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if f.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\.Insights/components/(?P<resourceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/favorites/(?P<favoriteId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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)
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	resourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceName")])
	if err != nil {
		return nil, err
	}
	favoriteIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("favoriteId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := f.srv.Get(req.Context(), resourceGroupNameParam, resourceNameParam, favoriteIDParam, 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).ComponentFavorite, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (f *FavoritesServerTransport) dispatchList(req *http.Request) (*http.Response, error) {
	if f.srv.List == nil {
		return nil, &nonRetriableError{errors.New("fake for method List not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Insights/components/(?P<resourceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/favorites`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 3 {
		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
	}
	resourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceName")])
	if err != nil {
		return nil, err
	}
	favoriteTypeUnescaped, err := url.QueryUnescape(qp.Get("favoriteType"))
	if err != nil {
		return nil, err
	}
	favoriteTypeParam := getOptional(armapplicationinsights.FavoriteType(favoriteTypeUnescaped))
	sourceTypeUnescaped, err := url.QueryUnescape(qp.Get("sourceType"))
	if err != nil {
		return nil, err
	}
	sourceTypeParam := getOptional(armapplicationinsights.FavoriteSourceType(sourceTypeUnescaped))
	canFetchContentUnescaped, err := url.QueryUnescape(qp.Get("canFetchContent"))
	if err != nil {
		return nil, err
	}
	canFetchContentParam, err := parseOptional(canFetchContentUnescaped, strconv.ParseBool)
	if err != nil {
		return nil, err
	}
	tagsUnescaped, err := url.QueryUnescape(qp.Get("tags"))
	if err != nil {
		return nil, err
	}
	tagsParam := splitHelper(tagsUnescaped, ",")
	var options *armapplicationinsights.FavoritesClientListOptions
	if favoriteTypeParam != nil || sourceTypeParam != nil || canFetchContentParam != nil || len(tagsParam) > 0 {
		options = &armapplicationinsights.FavoritesClientListOptions{
			FavoriteType:    favoriteTypeParam,
			SourceType:      sourceTypeParam,
			CanFetchContent: canFetchContentParam,
			Tags:            tagsParam,
		}
	}
	respr, errRespr := f.srv.List(req.Context(), resourceGroupNameParam, resourceNameParam, options)
	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).ComponentFavoriteArray, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (f *FavoritesServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) {
	if f.srv.Update == nil {
		return nil, &nonRetriableError{errors.New("fake for method Update not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Insights/components/(?P<resourceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/favorites/(?P<favoriteId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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)
	}
	body, err := server.UnmarshalRequestAsJSON[armapplicationinsights.ComponentFavorite](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	resourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceName")])
	if err != nil {
		return nil, err
	}
	favoriteIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("favoriteId")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := f.srv.Update(req.Context(), resourceGroupNameParam, resourceNameParam, favoriteIDParam, 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).ComponentFavorite, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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