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

// EntitiesServer is a fake server for instances of the armcloudhealth.EntitiesClient type.
type EntitiesServer struct {
	// CreateOrUpdate is the fake for method EntitiesClient.CreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	CreateOrUpdate func(ctx context.Context, resourceGroupName string, healthModelName string, entityName string, resource armcloudhealth.Entity, options *armcloudhealth.EntitiesClientCreateOrUpdateOptions) (resp azfake.Responder[armcloudhealth.EntitiesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// Delete is the fake for method EntitiesClient.Delete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent
	Delete func(ctx context.Context, resourceGroupName string, healthModelName string, entityName string, options *armcloudhealth.EntitiesClientDeleteOptions) (resp azfake.Responder[armcloudhealth.EntitiesClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method EntitiesClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, healthModelName string, entityName string, options *armcloudhealth.EntitiesClientGetOptions) (resp azfake.Responder[armcloudhealth.EntitiesClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByHealthModelPager is the fake for method EntitiesClient.NewListByHealthModelPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByHealthModelPager func(resourceGroupName string, healthModelName string, options *armcloudhealth.EntitiesClientListByHealthModelOptions) (resp azfake.PagerResponder[armcloudhealth.EntitiesClientListByHealthModelResponse])
}

// NewEntitiesServerTransport creates a new instance of EntitiesServerTransport with the provided implementation.
// The returned EntitiesServerTransport instance is connected to an instance of armcloudhealth.EntitiesClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewEntitiesServerTransport(srv *EntitiesServer) *EntitiesServerTransport {
	return &EntitiesServerTransport{
		srv:                       srv,
		newListByHealthModelPager: newTracker[azfake.PagerResponder[armcloudhealth.EntitiesClientListByHealthModelResponse]](),
	}
}

// EntitiesServerTransport connects instances of armcloudhealth.EntitiesClient to instances of EntitiesServer.
// Don't use this type directly, use NewEntitiesServerTransport instead.
type EntitiesServerTransport struct {
	srv                       *EntitiesServer
	newListByHealthModelPager *tracker[azfake.PagerResponder[armcloudhealth.EntitiesClientListByHealthModelResponse]]
}

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

func (e *EntitiesServerTransport) 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 entitiesServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = entitiesServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "EntitiesClient.CreateOrUpdate":
				res.resp, res.err = e.dispatchCreateOrUpdate(req)
			case "EntitiesClient.Delete":
				res.resp, res.err = e.dispatchDelete(req)
			case "EntitiesClient.Get":
				res.resp, res.err = e.dispatchGet(req)
			case "EntitiesClient.NewListByHealthModelPager":
				res.resp, res.err = e.dispatchNewListByHealthModelPager(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 (e *EntitiesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if e.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\.CloudHealth/healthmodels/(?P<healthModelName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/entities/(?P<entityName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 5 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armcloudhealth.Entity](req)
	if err != nil {
		return nil, err
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")])
	if err != nil {
		return nil, err
	}
	entityNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("entityName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := e.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, healthModelNameParam, entityNameParam, 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).Entity, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (e *EntitiesServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) {
	if e.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\.CloudHealth/healthmodels/(?P<healthModelName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/entities/(?P<entityName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if 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
	}
	healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")])
	if err != nil {
		return nil, err
	}
	entityNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("entityName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := e.srv.Delete(req.Context(), resourceGroupNameParam, healthModelNameParam, entityNameParam, 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 (e *EntitiesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if e.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\.CloudHealth/healthmodels/(?P<healthModelName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/entities/(?P<entityName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if 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
	}
	healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")])
	if err != nil {
		return nil, err
	}
	entityNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("entityName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := e.srv.Get(req.Context(), resourceGroupNameParam, healthModelNameParam, entityNameParam, 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).Entity, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (e *EntitiesServerTransport) dispatchNewListByHealthModelPager(req *http.Request) (*http.Response, error) {
	if e.srv.NewListByHealthModelPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListByHealthModelPager not implemented")}
	}
	newListByHealthModelPager := e.newListByHealthModelPager.get(req)
	if newListByHealthModelPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CloudHealth/healthmodels/(?P<healthModelName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/entities`
		regex := regexp.MustCompile(regexStr)
		matches := regex.FindStringSubmatch(req.URL.EscapedPath())
		if 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
		}
		timestampUnescaped, err := url.QueryUnescape(qp.Get("timestamp"))
		if err != nil {
			return nil, err
		}
		timestampParam, err := parseOptional(timestampUnescaped, func(v string) (time.Time, error) { return time.Parse(time.RFC3339Nano, v) })
		if err != nil {
			return nil, err
		}
		healthModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthModelName")])
		if err != nil {
			return nil, err
		}
		var options *armcloudhealth.EntitiesClientListByHealthModelOptions
		if timestampParam != nil {
			options = &armcloudhealth.EntitiesClientListByHealthModelOptions{
				Timestamp: timestampParam,
			}
		}
		resp := e.srv.NewListByHealthModelPager(resourceGroupNameParam, healthModelNameParam, options)
		newListByHealthModelPager = &resp
		e.newListByHealthModelPager.add(req, newListByHealthModelPager)
		server.PagerResponderInjectNextLinks(newListByHealthModelPager, req, func(page *armcloudhealth.EntitiesClientListByHealthModelResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListByHealthModelPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		e.newListByHealthModelPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListByHealthModelPager) {
		e.newListByHealthModelPager.remove(req)
	}
	return resp, nil
}

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