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

// AnalyticsItemsServer is a fake server for instances of the armapplicationinsights.AnalyticsItemsClient type.
type AnalyticsItemsServer struct {
	// Delete is the fake for method AnalyticsItemsClient.Delete
	// HTTP status codes to indicate success: http.StatusOK
	Delete func(ctx context.Context, resourceGroupName string, resourceName string, scopePath armapplicationinsights.ItemScopePath, options *armapplicationinsights.AnalyticsItemsClientDeleteOptions) (resp azfake.Responder[armapplicationinsights.AnalyticsItemsClientDeleteResponse], errResp azfake.ErrorResponder)

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

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

	// Put is the fake for method AnalyticsItemsClient.Put
	// HTTP status codes to indicate success: http.StatusOK
	Put func(ctx context.Context, resourceGroupName string, resourceName string, scopePath armapplicationinsights.ItemScopePath, itemProperties armapplicationinsights.ComponentAnalyticsItem, options *armapplicationinsights.AnalyticsItemsClientPutOptions) (resp azfake.Responder[armapplicationinsights.AnalyticsItemsClientPutResponse], errResp azfake.ErrorResponder)
}

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

// AnalyticsItemsServerTransport connects instances of armapplicationinsights.AnalyticsItemsClient to instances of AnalyticsItemsServer.
// Don't use this type directly, use NewAnalyticsItemsServerTransport instead.
type AnalyticsItemsServerTransport struct {
	srv *AnalyticsItemsServer
}

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

func (a *AnalyticsItemsServerTransport) 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 analyticsItemsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = analyticsItemsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "AnalyticsItemsClient.Delete":
				res.resp, res.err = a.dispatchDelete(req)
			case "AnalyticsItemsClient.Get":
				res.resp, res.err = a.dispatchGet(req)
			case "AnalyticsItemsClient.List":
				res.resp, res.err = a.dispatchList(req)
			case "AnalyticsItemsClient.Put":
				res.resp, res.err = a.dispatchPut(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 (a *AnalyticsItemsServerTransport) 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\.insights/components/(?P<resourceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P<scopePath>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/item`
	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
	}
	resourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceName")])
	if err != nil {
		return nil, err
	}
	scopePathParam, err := parseWithCast(matches[regex.SubexpIndex("scopePath")], func(v string) (armapplicationinsights.ItemScopePath, error) {
		p, unescapeErr := url.PathUnescape(v)
		if unescapeErr != nil {
			return "", unescapeErr
		}
		return armapplicationinsights.ItemScopePath(p), nil
	})
	if err != nil {
		return nil, err
	}
	iDUnescaped, err := url.QueryUnescape(qp.Get("id"))
	if err != nil {
		return nil, err
	}
	iDParam := getOptional(iDUnescaped)
	nameUnescaped, err := url.QueryUnescape(qp.Get("name"))
	if err != nil {
		return nil, err
	}
	nameParam := getOptional(nameUnescaped)
	var options *armapplicationinsights.AnalyticsItemsClientDeleteOptions
	if iDParam != nil || nameParam != nil {
		options = &armapplicationinsights.AnalyticsItemsClientDeleteOptions{
			ID:   iDParam,
			Name: nameParam,
		}
	}
	respr, errRespr := a.srv.Delete(req.Context(), resourceGroupNameParam, resourceNameParam, scopePathParam, 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.NewResponse(respContent, req, nil)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (a *AnalyticsItemsServerTransport) 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\.insights/components/(?P<resourceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P<scopePath>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/item`
	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
	}
	resourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceName")])
	if err != nil {
		return nil, err
	}
	scopePathParam, err := parseWithCast(matches[regex.SubexpIndex("scopePath")], func(v string) (armapplicationinsights.ItemScopePath, error) {
		p, unescapeErr := url.PathUnescape(v)
		if unescapeErr != nil {
			return "", unescapeErr
		}
		return armapplicationinsights.ItemScopePath(p), nil
	})
	if err != nil {
		return nil, err
	}
	iDUnescaped, err := url.QueryUnescape(qp.Get("id"))
	if err != nil {
		return nil, err
	}
	iDParam := getOptional(iDUnescaped)
	nameUnescaped, err := url.QueryUnescape(qp.Get("name"))
	if err != nil {
		return nil, err
	}
	nameParam := getOptional(nameUnescaped)
	var options *armapplicationinsights.AnalyticsItemsClientGetOptions
	if iDParam != nil || nameParam != nil {
		options = &armapplicationinsights.AnalyticsItemsClientGetOptions{
			ID:   iDParam,
			Name: nameParam,
		}
	}
	respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, resourceNameParam, scopePathParam, 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).ComponentAnalyticsItem, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (a *AnalyticsItemsServerTransport) dispatchList(req *http.Request) (*http.Response, error) {
	if a.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~%@]+)/(?P<scopePath>[!#&$-;=?-\[\]_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)
	}
	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
	}
	scopePathParam, err := parseWithCast(matches[regex.SubexpIndex("scopePath")], func(v string) (armapplicationinsights.ItemScopePath, error) {
		p, unescapeErr := url.PathUnescape(v)
		if unescapeErr != nil {
			return "", unescapeErr
		}
		return armapplicationinsights.ItemScopePath(p), nil
	})
	if err != nil {
		return nil, err
	}
	scopeUnescaped, err := url.QueryUnescape(qp.Get("scope"))
	if err != nil {
		return nil, err
	}
	scopeParam := getOptional(armapplicationinsights.ItemScope(scopeUnescaped))
	typeUnescaped, err := url.QueryUnescape(qp.Get("type"))
	if err != nil {
		return nil, err
	}
	typeParam := getOptional(armapplicationinsights.ItemTypeParameter(typeUnescaped))
	includeContentUnescaped, err := url.QueryUnescape(qp.Get("includeContent"))
	if err != nil {
		return nil, err
	}
	includeContentParam, err := parseOptional(includeContentUnescaped, strconv.ParseBool)
	if err != nil {
		return nil, err
	}
	var options *armapplicationinsights.AnalyticsItemsClientListOptions
	if scopeParam != nil || typeParam != nil || includeContentParam != nil {
		options = &armapplicationinsights.AnalyticsItemsClientListOptions{
			Scope:          scopeParam,
			Type:           typeParam,
			IncludeContent: includeContentParam,
		}
	}
	respr, errRespr := a.srv.List(req.Context(), resourceGroupNameParam, resourceNameParam, scopePathParam, 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).ComponentAnalyticsItemArray, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (a *AnalyticsItemsServerTransport) dispatchPut(req *http.Request) (*http.Response, error) {
	if a.srv.Put == nil {
		return nil, &nonRetriableError{errors.New("fake for method Put 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~%@]+)/(?P<scopePath>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/item`
	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()
	body, err := server.UnmarshalRequestAsJSON[armapplicationinsights.ComponentAnalyticsItem](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
	}
	scopePathParam, err := parseWithCast(matches[regex.SubexpIndex("scopePath")], func(v string) (armapplicationinsights.ItemScopePath, error) {
		p, unescapeErr := url.PathUnescape(v)
		if unescapeErr != nil {
			return "", unescapeErr
		}
		return armapplicationinsights.ItemScopePath(p), nil
	})
	if err != nil {
		return nil, err
	}
	overrideItemUnescaped, err := url.QueryUnescape(qp.Get("overrideItem"))
	if err != nil {
		return nil, err
	}
	overrideItemParam, err := parseOptional(overrideItemUnescaped, strconv.ParseBool)
	if err != nil {
		return nil, err
	}
	var options *armapplicationinsights.AnalyticsItemsClientPutOptions
	if overrideItemParam != nil {
		options = &armapplicationinsights.AnalyticsItemsClientPutOptions{
			OverrideItem: overrideItemParam,
		}
	}
	respr, errRespr := a.srv.Put(req.Context(), resourceGroupNameParam, resourceNameParam, scopePathParam, body, 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).ComponentAnalyticsItem, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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