// 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/dnsresolver/armdnsresolver"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
)

// DNSSecurityRulesServer is a fake server for instances of the armdnsresolver.DNSSecurityRulesClient type.
type DNSSecurityRulesServer struct {
	// BeginCreateOrUpdate is the fake for method DNSSecurityRulesClient.BeginCreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, dnsResolverPolicyName string, dnsSecurityRuleName string, parameters armdnsresolver.DNSSecurityRule, options *armdnsresolver.DNSSecurityRulesClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armdnsresolver.DNSSecurityRulesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// BeginDelete is the fake for method DNSSecurityRulesClient.BeginDelete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent
	BeginDelete func(ctx context.Context, resourceGroupName string, dnsResolverPolicyName string, dnsSecurityRuleName string, options *armdnsresolver.DNSSecurityRulesClientBeginDeleteOptions) (resp azfake.PollerResponder[armdnsresolver.DNSSecurityRulesClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method DNSSecurityRulesClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, dnsResolverPolicyName string, dnsSecurityRuleName string, options *armdnsresolver.DNSSecurityRulesClientGetOptions) (resp azfake.Responder[armdnsresolver.DNSSecurityRulesClientGetResponse], errResp azfake.ErrorResponder)

	// NewListPager is the fake for method DNSSecurityRulesClient.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(resourceGroupName string, dnsResolverPolicyName string, options *armdnsresolver.DNSSecurityRulesClientListOptions) (resp azfake.PagerResponder[armdnsresolver.DNSSecurityRulesClientListResponse])

	// BeginUpdate is the fake for method DNSSecurityRulesClient.BeginUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted
	BeginUpdate func(ctx context.Context, resourceGroupName string, dnsResolverPolicyName string, dnsSecurityRuleName string, parameters armdnsresolver.DNSSecurityRulePatch, options *armdnsresolver.DNSSecurityRulesClientBeginUpdateOptions) (resp azfake.PollerResponder[armdnsresolver.DNSSecurityRulesClientUpdateResponse], errResp azfake.ErrorResponder)
}

// NewDNSSecurityRulesServerTransport creates a new instance of DNSSecurityRulesServerTransport with the provided implementation.
// The returned DNSSecurityRulesServerTransport instance is connected to an instance of armdnsresolver.DNSSecurityRulesClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewDNSSecurityRulesServerTransport(srv *DNSSecurityRulesServer) *DNSSecurityRulesServerTransport {
	return &DNSSecurityRulesServerTransport{
		srv:                 srv,
		beginCreateOrUpdate: newTracker[azfake.PollerResponder[armdnsresolver.DNSSecurityRulesClientCreateOrUpdateResponse]](),
		beginDelete:         newTracker[azfake.PollerResponder[armdnsresolver.DNSSecurityRulesClientDeleteResponse]](),
		newListPager:        newTracker[azfake.PagerResponder[armdnsresolver.DNSSecurityRulesClientListResponse]](),
		beginUpdate:         newTracker[azfake.PollerResponder[armdnsresolver.DNSSecurityRulesClientUpdateResponse]](),
	}
}

// DNSSecurityRulesServerTransport connects instances of armdnsresolver.DNSSecurityRulesClient to instances of DNSSecurityRulesServer.
// Don't use this type directly, use NewDNSSecurityRulesServerTransport instead.
type DNSSecurityRulesServerTransport struct {
	srv                 *DNSSecurityRulesServer
	beginCreateOrUpdate *tracker[azfake.PollerResponder[armdnsresolver.DNSSecurityRulesClientCreateOrUpdateResponse]]
	beginDelete         *tracker[azfake.PollerResponder[armdnsresolver.DNSSecurityRulesClientDeleteResponse]]
	newListPager        *tracker[azfake.PagerResponder[armdnsresolver.DNSSecurityRulesClientListResponse]]
	beginUpdate         *tracker[azfake.PollerResponder[armdnsresolver.DNSSecurityRulesClientUpdateResponse]]
}

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

func (d *DNSSecurityRulesServerTransport) 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 dnsSecurityRulesServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = dnsSecurityRulesServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "DNSSecurityRulesClient.BeginCreateOrUpdate":
				res.resp, res.err = d.dispatchBeginCreateOrUpdate(req)
			case "DNSSecurityRulesClient.BeginDelete":
				res.resp, res.err = d.dispatchBeginDelete(req)
			case "DNSSecurityRulesClient.Get":
				res.resp, res.err = d.dispatchGet(req)
			case "DNSSecurityRulesClient.NewListPager":
				res.resp, res.err = d.dispatchNewListPager(req)
			case "DNSSecurityRulesClient.BeginUpdate":
				res.resp, res.err = d.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 (d *DNSSecurityRulesServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if d.srv.BeginCreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")}
	}
	beginCreateOrUpdate := d.beginCreateOrUpdate.get(req)
	if beginCreateOrUpdate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Network/dnsResolverPolicies/(?P<dnsResolverPolicyName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dnsSecurityRules/(?P<dnsSecurityRuleName>[!#&$-;=?-\[\]_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)
		}
		body, err := server.UnmarshalRequestAsJSON[armdnsresolver.DNSSecurityRule](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		dnsResolverPolicyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsResolverPolicyName")])
		if err != nil {
			return nil, err
		}
		dnsSecurityRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsSecurityRuleName")])
		if err != nil {
			return nil, err
		}
		ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match"))
		ifNoneMatchParam := getOptional(getHeaderValue(req.Header, "If-None-Match"))
		var options *armdnsresolver.DNSSecurityRulesClientBeginCreateOrUpdateOptions
		if ifMatchParam != nil || ifNoneMatchParam != nil {
			options = &armdnsresolver.DNSSecurityRulesClientBeginCreateOrUpdateOptions{
				IfMatch:     ifMatchParam,
				IfNoneMatch: ifNoneMatchParam,
			}
		}
		respr, errRespr := d.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, dnsResolverPolicyNameParam, dnsSecurityRuleNameParam, body, options)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreateOrUpdate = &respr
		d.beginCreateOrUpdate.add(req, beginCreateOrUpdate)
	}

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

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

	return resp, nil
}

func (d *DNSSecurityRulesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) {
	if d.srv.BeginDelete == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")}
	}
	beginDelete := d.beginDelete.get(req)
	if beginDelete == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Network/dnsResolverPolicies/(?P<dnsResolverPolicyName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dnsSecurityRules/(?P<dnsSecurityRuleName>[!#&$-;=?-\[\]_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)
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		dnsResolverPolicyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsResolverPolicyName")])
		if err != nil {
			return nil, err
		}
		dnsSecurityRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsSecurityRuleName")])
		if err != nil {
			return nil, err
		}
		ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match"))
		var options *armdnsresolver.DNSSecurityRulesClientBeginDeleteOptions
		if ifMatchParam != nil {
			options = &armdnsresolver.DNSSecurityRulesClientBeginDeleteOptions{
				IfMatch: ifMatchParam,
			}
		}
		respr, errRespr := d.srv.BeginDelete(req.Context(), resourceGroupNameParam, dnsResolverPolicyNameParam, dnsSecurityRuleNameParam, options)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginDelete = &respr
		d.beginDelete.add(req, beginDelete)
	}

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

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

	return resp, nil
}

func (d *DNSSecurityRulesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if d.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\.Network/dnsResolverPolicies/(?P<dnsResolverPolicyName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dnsSecurityRules/(?P<dnsSecurityRuleName>[!#&$-;=?-\[\]_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)
	}
	resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
	if err != nil {
		return nil, err
	}
	dnsResolverPolicyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsResolverPolicyName")])
	if err != nil {
		return nil, err
	}
	dnsSecurityRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsSecurityRuleName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := d.srv.Get(req.Context(), resourceGroupNameParam, dnsResolverPolicyNameParam, dnsSecurityRuleNameParam, 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).DNSSecurityRule, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (d *DNSSecurityRulesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) {
	if d.srv.NewListPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")}
	}
	newListPager := d.newListPager.get(req)
	if newListPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Network/dnsResolverPolicies/(?P<dnsResolverPolicyName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dnsSecurityRules`
		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)
		}
		qp := req.URL.Query()
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		dnsResolverPolicyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsResolverPolicyName")])
		if err != nil {
			return nil, err
		}
		topUnescaped, err := url.QueryUnescape(qp.Get("$top"))
		if err != nil {
			return nil, err
		}
		topParam, err := parseOptional(topUnescaped, func(v string) (int32, error) {
			p, parseErr := strconv.ParseInt(v, 10, 32)
			if parseErr != nil {
				return 0, parseErr
			}
			return int32(p), nil
		})
		if err != nil {
			return nil, err
		}
		var options *armdnsresolver.DNSSecurityRulesClientListOptions
		if topParam != nil {
			options = &armdnsresolver.DNSSecurityRulesClientListOptions{
				Top: topParam,
			}
		}
		resp := d.srv.NewListPager(resourceGroupNameParam, dnsResolverPolicyNameParam, options)
		newListPager = &resp
		d.newListPager.add(req, newListPager)
		server.PagerResponderInjectNextLinks(newListPager, req, func(page *armdnsresolver.DNSSecurityRulesClientListResponse, createLink func() string) {
			page.NextLink = to.Ptr(createLink())
		})
	}
	resp, err := server.PagerResponderNext(newListPager, req)
	if err != nil {
		return nil, err
	}
	if !contains([]int{http.StatusOK}, resp.StatusCode) {
		d.newListPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListPager) {
		d.newListPager.remove(req)
	}
	return resp, nil
}

func (d *DNSSecurityRulesServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) {
	if d.srv.BeginUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")}
	}
	beginUpdate := d.beginUpdate.get(req)
	if beginUpdate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Network/dnsResolverPolicies/(?P<dnsResolverPolicyName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dnsSecurityRules/(?P<dnsSecurityRuleName>[!#&$-;=?-\[\]_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)
		}
		body, err := server.UnmarshalRequestAsJSON[armdnsresolver.DNSSecurityRulePatch](req)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		dnsResolverPolicyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsResolverPolicyName")])
		if err != nil {
			return nil, err
		}
		dnsSecurityRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsSecurityRuleName")])
		if err != nil {
			return nil, err
		}
		ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match"))
		var options *armdnsresolver.DNSSecurityRulesClientBeginUpdateOptions
		if ifMatchParam != nil {
			options = &armdnsresolver.DNSSecurityRulesClientBeginUpdateOptions{
				IfMatch: ifMatchParam,
			}
		}
		respr, errRespr := d.srv.BeginUpdate(req.Context(), resourceGroupNameParam, dnsResolverPolicyNameParam, dnsSecurityRuleNameParam, body, options)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginUpdate = &respr
		d.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) {
		d.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) {
		d.beginUpdate.remove(req)
	}

	return resp, nil
}

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