// 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/containerservicefleet/armcontainerservicefleet/v3"
	"net/http"
	"net/url"
	"regexp"
)

// GatesServer is a fake server for instances of the armcontainerservicefleet.GatesClient type.
type GatesServer struct {
	// Get is the fake for method GatesClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, fleetName string, gateName string, options *armcontainerservicefleet.GatesClientGetOptions) (resp azfake.Responder[armcontainerservicefleet.GatesClientGetResponse], errResp azfake.ErrorResponder)

	// NewListByFleetPager is the fake for method GatesClient.NewListByFleetPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListByFleetPager func(resourceGroupName string, fleetName string, options *armcontainerservicefleet.GatesClientListByFleetOptions) (resp azfake.PagerResponder[armcontainerservicefleet.GatesClientListByFleetResponse])

	// BeginUpdate is the fake for method GatesClient.BeginUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginUpdate func(ctx context.Context, resourceGroupName string, fleetName string, gateName string, properties armcontainerservicefleet.GatePatch, options *armcontainerservicefleet.GatesClientBeginUpdateOptions) (resp azfake.PollerResponder[armcontainerservicefleet.GatesClientUpdateResponse], errResp azfake.ErrorResponder)
}

// NewGatesServerTransport creates a new instance of GatesServerTransport with the provided implementation.
// The returned GatesServerTransport instance is connected to an instance of armcontainerservicefleet.GatesClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewGatesServerTransport(srv *GatesServer) *GatesServerTransport {
	return &GatesServerTransport{
		srv:                 srv,
		newListByFleetPager: newTracker[azfake.PagerResponder[armcontainerservicefleet.GatesClientListByFleetResponse]](),
		beginUpdate:         newTracker[azfake.PollerResponder[armcontainerservicefleet.GatesClientUpdateResponse]](),
	}
}

// GatesServerTransport connects instances of armcontainerservicefleet.GatesClient to instances of GatesServer.
// Don't use this type directly, use NewGatesServerTransport instead.
type GatesServerTransport struct {
	srv                 *GatesServer
	newListByFleetPager *tracker[azfake.PagerResponder[armcontainerservicefleet.GatesClientListByFleetResponse]]
	beginUpdate         *tracker[azfake.PollerResponder[armcontainerservicefleet.GatesClientUpdateResponse]]
}

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

func (g *GatesServerTransport) 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 gatesServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = gatesServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "GatesClient.Get":
				res.resp, res.err = g.dispatchGet(req)
			case "GatesClient.NewListByFleetPager":
				res.resp, res.err = g.dispatchNewListByFleetPager(req)
			case "GatesClient.BeginUpdate":
				res.resp, res.err = g.dispatchBeginUpdate(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 (g *GatesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if g.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\.ContainerService/fleets/(?P<fleetName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/gates/(?P<gateName>[!#&$-;=?-\[\]_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
	}
	fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")])
	if err != nil {
		return nil, err
	}
	gateNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("gateName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := g.srv.Get(req.Context(), resourceGroupNameParam, fleetNameParam, gateNameParam, 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).Gate, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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

func (g *GatesServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) {
	if g.srv.BeginUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")}
	}
	beginUpdate := g.beginUpdate.get(req)
	if beginUpdate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ContainerService/fleets/(?P<fleetName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/gates/(?P<gateName>[!#&$-;=?-\[\]_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[armcontainerservicefleet.GatePatch](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match"))
		ifNoneMatchParam := getOptional(getHeaderValue(req.Header, "If-None-Match"))
		fleetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("fleetName")])
		if err != nil {
			return nil, err
		}
		gateNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("gateName")])
		if err != nil {
			return nil, err
		}
		var options *armcontainerservicefleet.GatesClientBeginUpdateOptions
		if ifMatchParam != nil || ifNoneMatchParam != nil {
			options = &armcontainerservicefleet.GatesClientBeginUpdateOptions{
				IfMatch:     ifMatchParam,
				IfNoneMatch: ifNoneMatchParam,
			}
		}
		respr, errRespr := g.srv.BeginUpdate(req.Context(), resourceGroupNameParam, fleetNameParam, gateNameParam, body, options)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginUpdate = &respr
		g.beginUpdate.add(req, beginUpdate)
	}

	resp, err := server.PollerResponderNext(beginUpdate, req)
	if err != nil {
		return nil, err
	}

	if !contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) {
		g.beginUpdate.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)}
	}
	if !server.PollerResponderMore(beginUpdate) {
		g.beginUpdate.remove(req)
	}

	return resp, nil
}

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