// 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) Go Code Generator. DO NOT EDIT.

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/peering/armpeering/v2"
	"net/http"
	"net/url"
	"regexp"
)

// LookingGlassServer is a fake server for instances of the armpeering.LookingGlassClient type.
type LookingGlassServer struct {
	// Invoke is the fake for method LookingGlassClient.Invoke
	// HTTP status codes to indicate success: http.StatusOK
	Invoke func(ctx context.Context, command armpeering.LookingGlassCommand, sourceType armpeering.LookingGlassSourceType, sourceLocation string, destinationIP string, options *armpeering.LookingGlassClientInvokeOptions) (resp azfake.Responder[armpeering.LookingGlassClientInvokeResponse], errResp azfake.ErrorResponder)
}

// NewLookingGlassServerTransport creates a new instance of LookingGlassServerTransport with the provided implementation.
// The returned LookingGlassServerTransport instance is connected to an instance of armpeering.LookingGlassClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewLookingGlassServerTransport(srv *LookingGlassServer) *LookingGlassServerTransport {
	return &LookingGlassServerTransport{srv: srv}
}

// LookingGlassServerTransport connects instances of armpeering.LookingGlassClient to instances of LookingGlassServer.
// Don't use this type directly, use NewLookingGlassServerTransport instead.
type LookingGlassServerTransport struct {
	srv *LookingGlassServer
}

// Do implements the policy.Transporter interface for LookingGlassServerTransport.
func (l *LookingGlassServerTransport) 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 *LookingGlassServerTransport) 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 lookingGlassServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = lookingGlassServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "LookingGlassClient.Invoke":
				res.resp, res.err = l.dispatchInvoke(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 *LookingGlassServerTransport) dispatchInvoke(req *http.Request) (*http.Response, error) {
	if l.srv.Invoke == nil {
		return nil, &nonRetriableError{errors.New("fake for method Invoke not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Peering/lookingGlass`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 2 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	qp := req.URL.Query()
	commandParam, err := parseWithCast(qp.Get("command"), func(v string) (armpeering.LookingGlassCommand, error) {
		p, unescapeErr := url.QueryUnescape(v)
		if unescapeErr != nil {
			return "", unescapeErr
		}
		return armpeering.LookingGlassCommand(p), nil
	})
	if err != nil {
		return nil, err
	}
	sourceTypeParam, err := parseWithCast(qp.Get("sourceType"), func(v string) (armpeering.LookingGlassSourceType, error) {
		p, unescapeErr := url.QueryUnescape(v)
		if unescapeErr != nil {
			return "", unescapeErr
		}
		return armpeering.LookingGlassSourceType(p), nil
	})
	if err != nil {
		return nil, err
	}
	sourceLocationParam, err := url.QueryUnescape(qp.Get("sourceLocation"))
	if err != nil {
		return nil, err
	}
	destinationIPParam, err := url.QueryUnescape(qp.Get("destinationIP"))
	if err != nil {
		return nil, err
	}
	respr, errRespr := l.srv.Invoke(req.Context(), commandParam, sourceTypeParam, sourceLocationParam, destinationIPParam, 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).LookingGlassOutput, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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