//go:build go1.18
// +build go1.18

// 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/resourcemanager/timeseriesinsights/armtimeseriesinsights"
	"net/http"
	"net/url"
	"regexp"
)

// EnvironmentsServer is a fake server for instances of the armtimeseriesinsights.EnvironmentsClient type.
type EnvironmentsServer struct {
	// BeginCreateOrUpdate is the fake for method EnvironmentsClient.BeginCreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated, http.StatusNotFound
	BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, environmentName string, parameters armtimeseriesinsights.EnvironmentCreateOrUpdateParametersClassification, options *armtimeseriesinsights.EnvironmentsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armtimeseriesinsights.EnvironmentsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// Delete is the fake for method EnvironmentsClient.Delete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent
	Delete func(ctx context.Context, resourceGroupName string, environmentName string, options *armtimeseriesinsights.EnvironmentsClientDeleteOptions) (resp azfake.Responder[armtimeseriesinsights.EnvironmentsClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method EnvironmentsClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, resourceGroupName string, environmentName string, options *armtimeseriesinsights.EnvironmentsClientGetOptions) (resp azfake.Responder[armtimeseriesinsights.EnvironmentsClientGetResponse], errResp azfake.ErrorResponder)

	// ListByResourceGroup is the fake for method EnvironmentsClient.ListByResourceGroup
	// HTTP status codes to indicate success: http.StatusOK
	ListByResourceGroup func(ctx context.Context, resourceGroupName string, options *armtimeseriesinsights.EnvironmentsClientListByResourceGroupOptions) (resp azfake.Responder[armtimeseriesinsights.EnvironmentsClientListByResourceGroupResponse], errResp azfake.ErrorResponder)

	// ListBySubscription is the fake for method EnvironmentsClient.ListBySubscription
	// HTTP status codes to indicate success: http.StatusOK
	ListBySubscription func(ctx context.Context, options *armtimeseriesinsights.EnvironmentsClientListBySubscriptionOptions) (resp azfake.Responder[armtimeseriesinsights.EnvironmentsClientListBySubscriptionResponse], errResp azfake.ErrorResponder)

	// BeginUpdate is the fake for method EnvironmentsClient.BeginUpdate
	// HTTP status codes to indicate success: http.StatusOK
	BeginUpdate func(ctx context.Context, resourceGroupName string, environmentName string, environmentUpdateParameters armtimeseriesinsights.EnvironmentUpdateParametersClassification, options *armtimeseriesinsights.EnvironmentsClientBeginUpdateOptions) (resp azfake.PollerResponder[armtimeseriesinsights.EnvironmentsClientUpdateResponse], errResp azfake.ErrorResponder)
}

// NewEnvironmentsServerTransport creates a new instance of EnvironmentsServerTransport with the provided implementation.
// The returned EnvironmentsServerTransport instance is connected to an instance of armtimeseriesinsights.EnvironmentsClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewEnvironmentsServerTransport(srv *EnvironmentsServer) *EnvironmentsServerTransport {
	return &EnvironmentsServerTransport{
		srv:                 srv,
		beginCreateOrUpdate: newTracker[azfake.PollerResponder[armtimeseriesinsights.EnvironmentsClientCreateOrUpdateResponse]](),
		beginUpdate:         newTracker[azfake.PollerResponder[armtimeseriesinsights.EnvironmentsClientUpdateResponse]](),
	}
}

// EnvironmentsServerTransport connects instances of armtimeseriesinsights.EnvironmentsClient to instances of EnvironmentsServer.
// Don't use this type directly, use NewEnvironmentsServerTransport instead.
type EnvironmentsServerTransport struct {
	srv                 *EnvironmentsServer
	beginCreateOrUpdate *tracker[azfake.PollerResponder[armtimeseriesinsights.EnvironmentsClientCreateOrUpdateResponse]]
	beginUpdate         *tracker[azfake.PollerResponder[armtimeseriesinsights.EnvironmentsClientUpdateResponse]]
}

// Do implements the policy.Transporter interface for EnvironmentsServerTransport.
func (e *EnvironmentsServerTransport) 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")}
	}

	var resp *http.Response
	var err error

	switch method {
	case "EnvironmentsClient.BeginCreateOrUpdate":
		resp, err = e.dispatchBeginCreateOrUpdate(req)
	case "EnvironmentsClient.Delete":
		resp, err = e.dispatchDelete(req)
	case "EnvironmentsClient.Get":
		resp, err = e.dispatchGet(req)
	case "EnvironmentsClient.ListByResourceGroup":
		resp, err = e.dispatchListByResourceGroup(req)
	case "EnvironmentsClient.ListBySubscription":
		resp, err = e.dispatchListBySubscription(req)
	case "EnvironmentsClient.BeginUpdate":
		resp, err = e.dispatchBeginUpdate(req)
	default:
		err = fmt.Errorf("unhandled API %s", method)
	}

	if err != nil {
		return nil, err
	}

	return resp, nil
}

func (e *EnvironmentsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if e.srv.BeginCreateOrUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")}
	}
	beginCreateOrUpdate := e.beginCreateOrUpdate.get(req)
	if beginCreateOrUpdate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.TimeSeriesInsights/environments/(?P<environmentName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		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)
		}
		raw, err := readRequestBody(req)
		if err != nil {
			return nil, err
		}
		body, err := unmarshalEnvironmentCreateOrUpdateParametersClassification(raw)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		environmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("environmentName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := e.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, environmentNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginCreateOrUpdate = &respr
		e.beginCreateOrUpdate.add(req, beginCreateOrUpdate)
	}

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

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

	return resp, nil
}

func (e *EnvironmentsServerTransport) 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\.TimeSeriesInsights/environments/(?P<environmentName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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
	}
	environmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("environmentName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := e.srv.Delete(req.Context(), resourceGroupNameParam, environmentNameParam, 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 *EnvironmentsServerTransport) 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\.TimeSeriesInsights/environments/(?P<environmentName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	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
	}
	environmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("environmentName")])
	if err != nil {
		return nil, err
	}
	expandUnescaped, err := url.QueryUnescape(qp.Get("$expand"))
	if err != nil {
		return nil, err
	}
	expandParam := getOptional(expandUnescaped)
	var options *armtimeseriesinsights.EnvironmentsClientGetOptions
	if expandParam != nil {
		options = &armtimeseriesinsights.EnvironmentsClientGetOptions{
			Expand: expandParam,
		}
	}
	respr, errRespr := e.srv.Get(req.Context(), resourceGroupNameParam, environmentNameParam, 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).EnvironmentResourceClassification, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (e *EnvironmentsServerTransport) dispatchListByResourceGroup(req *http.Request) (*http.Response, error) {
	if e.srv.ListByResourceGroup == nil {
		return nil, &nonRetriableError{errors.New("fake for method ListByResourceGroup not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.TimeSeriesInsights/environments`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 2 {
		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
	}
	respr, errRespr := e.srv.ListByResourceGroup(req.Context(), resourceGroupNameParam, 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).EnvironmentListResponse, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (e *EnvironmentsServerTransport) dispatchListBySubscription(req *http.Request) (*http.Response, error) {
	if e.srv.ListBySubscription == nil {
		return nil, &nonRetriableError{errors.New("fake for method ListBySubscription not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.TimeSeriesInsights/environments`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if matches == nil || len(matches) < 1 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	respr, errRespr := e.srv.ListBySubscription(req.Context(), 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).EnvironmentListResponse, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (e *EnvironmentsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) {
	if e.srv.BeginUpdate == nil {
		return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")}
	}
	beginUpdate := e.beginUpdate.get(req)
	if beginUpdate == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<resourceGroupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.TimeSeriesInsights/environments/(?P<environmentName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
		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)
		}
		raw, err := readRequestBody(req)
		if err != nil {
			return nil, err
		}
		body, err := unmarshalEnvironmentUpdateParametersClassification(raw)
		if err != nil {
			return nil, err
		}
		resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")])
		if err != nil {
			return nil, err
		}
		environmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("environmentName")])
		if err != nil {
			return nil, err
		}
		respr, errRespr := e.srv.BeginUpdate(req.Context(), resourceGroupNameParam, environmentNameParam, body, nil)
		if respErr := server.GetError(errRespr, req); respErr != nil {
			return nil, respErr
		}
		beginUpdate = &respr
		e.beginUpdate.add(req, beginUpdate)
	}

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

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

	return resp, nil
}
