// 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/appservice/armappservice/v5"
	"net/http"
	"net/url"
	"regexp"
	"time"
)

// CertificateOrdersDiagnosticsServer is a fake server for instances of the armappservice.CertificateOrdersDiagnosticsClient type.
type CertificateOrdersDiagnosticsServer struct {
	// GetAppServiceCertificateOrderDetectorResponse is the fake for method CertificateOrdersDiagnosticsClient.GetAppServiceCertificateOrderDetectorResponse
	// HTTP status codes to indicate success: http.StatusOK
	GetAppServiceCertificateOrderDetectorResponse func(ctx context.Context, resourceGroupName string, certificateOrderName string, detectorName string, options *armappservice.CertificateOrdersDiagnosticsClientGetAppServiceCertificateOrderDetectorResponseOptions) (resp azfake.Responder[armappservice.CertificateOrdersDiagnosticsClientGetAppServiceCertificateOrderDetectorResponseResponse], errResp azfake.ErrorResponder)

	// NewListAppServiceCertificateOrderDetectorResponsePager is the fake for method CertificateOrdersDiagnosticsClient.NewListAppServiceCertificateOrderDetectorResponsePager
	// HTTP status codes to indicate success: http.StatusOK
	NewListAppServiceCertificateOrderDetectorResponsePager func(resourceGroupName string, certificateOrderName string, options *armappservice.CertificateOrdersDiagnosticsClientListAppServiceCertificateOrderDetectorResponseOptions) (resp azfake.PagerResponder[armappservice.CertificateOrdersDiagnosticsClientListAppServiceCertificateOrderDetectorResponseResponse])
}

// NewCertificateOrdersDiagnosticsServerTransport creates a new instance of CertificateOrdersDiagnosticsServerTransport with the provided implementation.
// The returned CertificateOrdersDiagnosticsServerTransport instance is connected to an instance of armappservice.CertificateOrdersDiagnosticsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewCertificateOrdersDiagnosticsServerTransport(srv *CertificateOrdersDiagnosticsServer) *CertificateOrdersDiagnosticsServerTransport {
	return &CertificateOrdersDiagnosticsServerTransport{
		srv: srv,
		newListAppServiceCertificateOrderDetectorResponsePager: newTracker[azfake.PagerResponder[armappservice.CertificateOrdersDiagnosticsClientListAppServiceCertificateOrderDetectorResponseResponse]](),
	}
}

// CertificateOrdersDiagnosticsServerTransport connects instances of armappservice.CertificateOrdersDiagnosticsClient to instances of CertificateOrdersDiagnosticsServer.
// Don't use this type directly, use NewCertificateOrdersDiagnosticsServerTransport instead.
type CertificateOrdersDiagnosticsServerTransport struct {
	srv                                                    *CertificateOrdersDiagnosticsServer
	newListAppServiceCertificateOrderDetectorResponsePager *tracker[azfake.PagerResponder[armappservice.CertificateOrdersDiagnosticsClientListAppServiceCertificateOrderDetectorResponseResponse]]
}

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

func (c *CertificateOrdersDiagnosticsServerTransport) 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 certificateOrdersDiagnosticsServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = certificateOrdersDiagnosticsServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "CertificateOrdersDiagnosticsClient.GetAppServiceCertificateOrderDetectorResponse":
				res.resp, res.err = c.dispatchGetAppServiceCertificateOrderDetectorResponse(req)
			case "CertificateOrdersDiagnosticsClient.NewListAppServiceCertificateOrderDetectorResponsePager":
				res.resp, res.err = c.dispatchNewListAppServiceCertificateOrderDetectorResponsePager(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 (c *CertificateOrdersDiagnosticsServerTransport) dispatchGetAppServiceCertificateOrderDetectorResponse(req *http.Request) (*http.Response, error) {
	if c.srv.GetAppServiceCertificateOrderDetectorResponse == nil {
		return nil, &nonRetriableError{errors.New("fake for method GetAppServiceCertificateOrderDetectorResponse not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CertificateRegistration/certificateOrders/(?P<certificateOrderName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/detectors/(?P<detectorName>[!#&$-;=?-\[\]_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
	}
	certificateOrderNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("certificateOrderName")])
	if err != nil {
		return nil, err
	}
	detectorNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("detectorName")])
	if err != nil {
		return nil, err
	}
	startTimeUnescaped, err := url.QueryUnescape(qp.Get("startTime"))
	if err != nil {
		return nil, err
	}
	startTimeParam, err := parseOptional(startTimeUnescaped, func(v string) (time.Time, error) { return time.Parse(time.RFC3339Nano, v) })
	if err != nil {
		return nil, err
	}
	endTimeUnescaped, err := url.QueryUnescape(qp.Get("endTime"))
	if err != nil {
		return nil, err
	}
	endTimeParam, err := parseOptional(endTimeUnescaped, func(v string) (time.Time, error) { return time.Parse(time.RFC3339Nano, v) })
	if err != nil {
		return nil, err
	}
	timeGrainUnescaped, err := url.QueryUnescape(qp.Get("timeGrain"))
	if err != nil {
		return nil, err
	}
	timeGrainParam := getOptional(timeGrainUnescaped)
	var options *armappservice.CertificateOrdersDiagnosticsClientGetAppServiceCertificateOrderDetectorResponseOptions
	if startTimeParam != nil || endTimeParam != nil || timeGrainParam != nil {
		options = &armappservice.CertificateOrdersDiagnosticsClientGetAppServiceCertificateOrderDetectorResponseOptions{
			StartTime: startTimeParam,
			EndTime:   endTimeParam,
			TimeGrain: timeGrainParam,
		}
	}
	respr, errRespr := c.srv.GetAppServiceCertificateOrderDetectorResponse(req.Context(), resourceGroupNameParam, certificateOrderNameParam, detectorNameParam, 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).DetectorResponse, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (c *CertificateOrdersDiagnosticsServerTransport) dispatchNewListAppServiceCertificateOrderDetectorResponsePager(req *http.Request) (*http.Response, error) {
	if c.srv.NewListAppServiceCertificateOrderDetectorResponsePager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListAppServiceCertificateOrderDetectorResponsePager not implemented")}
	}
	newListAppServiceCertificateOrderDetectorResponsePager := c.newListAppServiceCertificateOrderDetectorResponsePager.get(req)
	if newListAppServiceCertificateOrderDetectorResponsePager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CertificateRegistration/certificateOrders/(?P<certificateOrderName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/detectors`
		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)
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		certificateOrderNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("certificateOrderName")])
		if err != nil {
			return nil, err
		}
		resp := c.srv.NewListAppServiceCertificateOrderDetectorResponsePager(resourceGroupNameParam, certificateOrderNameParam, nil)
		newListAppServiceCertificateOrderDetectorResponsePager = &resp
		c.newListAppServiceCertificateOrderDetectorResponsePager.add(req, newListAppServiceCertificateOrderDetectorResponsePager)
		server.PagerResponderInjectNextLinks(newListAppServiceCertificateOrderDetectorResponsePager, req, func(page *armappservice.CertificateOrdersDiagnosticsClientListAppServiceCertificateOrderDetectorResponseResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListAppServiceCertificateOrderDetectorResponsePager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		c.newListAppServiceCertificateOrderDetectorResponsePager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListAppServiceCertificateOrderDetectorResponsePager) {
		c.newListAppServiceCertificateOrderDetectorResponsePager.remove(req)
	}
	return resp, nil
}

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