// 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/datamigration/armdatamigration/v2"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
)

// TasksServer is a fake server for instances of the armdatamigration.TasksClient type.
type TasksServer struct {
	// Cancel is the fake for method TasksClient.Cancel
	// HTTP status codes to indicate success: http.StatusOK
	Cancel func(ctx context.Context, groupName string, serviceName string, projectName string, taskName string, options *armdatamigration.TasksClientCancelOptions) (resp azfake.Responder[armdatamigration.TasksClientCancelResponse], errResp azfake.ErrorResponder)

	// Command is the fake for method TasksClient.Command
	// HTTP status codes to indicate success: http.StatusOK
	Command func(ctx context.Context, groupName string, serviceName string, projectName string, taskName string, parameters armdatamigration.CommandPropertiesClassification, options *armdatamigration.TasksClientCommandOptions) (resp azfake.Responder[armdatamigration.TasksClientCommandResponse], errResp azfake.ErrorResponder)

	// CreateOrUpdate is the fake for method TasksClient.CreateOrUpdate
	// HTTP status codes to indicate success: http.StatusOK, http.StatusCreated
	CreateOrUpdate func(ctx context.Context, groupName string, serviceName string, projectName string, taskName string, parameters armdatamigration.ProjectTask, options *armdatamigration.TasksClientCreateOrUpdateOptions) (resp azfake.Responder[armdatamigration.TasksClientCreateOrUpdateResponse], errResp azfake.ErrorResponder)

	// Delete is the fake for method TasksClient.Delete
	// HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent
	Delete func(ctx context.Context, groupName string, serviceName string, projectName string, taskName string, options *armdatamigration.TasksClientDeleteOptions) (resp azfake.Responder[armdatamigration.TasksClientDeleteResponse], errResp azfake.ErrorResponder)

	// Get is the fake for method TasksClient.Get
	// HTTP status codes to indicate success: http.StatusOK
	Get func(ctx context.Context, groupName string, serviceName string, projectName string, taskName string, options *armdatamigration.TasksClientGetOptions) (resp azfake.Responder[armdatamigration.TasksClientGetResponse], errResp azfake.ErrorResponder)

	// NewListPager is the fake for method TasksClient.NewListPager
	// HTTP status codes to indicate success: http.StatusOK
	NewListPager func(groupName string, serviceName string, projectName string, options *armdatamigration.TasksClientListOptions) (resp azfake.PagerResponder[armdatamigration.TasksClientListResponse])

	// Update is the fake for method TasksClient.Update
	// HTTP status codes to indicate success: http.StatusOK
	Update func(ctx context.Context, groupName string, serviceName string, projectName string, taskName string, parameters armdatamigration.ProjectTask, options *armdatamigration.TasksClientUpdateOptions) (resp azfake.Responder[armdatamigration.TasksClientUpdateResponse], errResp azfake.ErrorResponder)
}

// NewTasksServerTransport creates a new instance of TasksServerTransport with the provided implementation.
// The returned TasksServerTransport instance is connected to an instance of armdatamigration.TasksClient via the
// azcore.ClientOptions.Transporter field in the client's constructor parameters.
func NewTasksServerTransport(srv *TasksServer) *TasksServerTransport {
	return &TasksServerTransport{
		srv:          srv,
		newListPager: newTracker[azfake.PagerResponder[armdatamigration.TasksClientListResponse]](),
	}
}

// TasksServerTransport connects instances of armdatamigration.TasksClient to instances of TasksServer.
// Don't use this type directly, use NewTasksServerTransport instead.
type TasksServerTransport struct {
	srv          *TasksServer
	newListPager *tracker[azfake.PagerResponder[armdatamigration.TasksClientListResponse]]
}

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

func (t *TasksServerTransport) 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 tasksServerTransportInterceptor != nil {
			res.resp, res.err, intercepted = tasksServerTransportInterceptor.Do(req)
		}
		if !intercepted {
			switch method {
			case "TasksClient.Cancel":
				res.resp, res.err = t.dispatchCancel(req)
			case "TasksClient.Command":
				res.resp, res.err = t.dispatchCommand(req)
			case "TasksClient.CreateOrUpdate":
				res.resp, res.err = t.dispatchCreateOrUpdate(req)
			case "TasksClient.Delete":
				res.resp, res.err = t.dispatchDelete(req)
			case "TasksClient.Get":
				res.resp, res.err = t.dispatchGet(req)
			case "TasksClient.NewListPager":
				res.resp, res.err = t.dispatchNewListPager(req)
			case "TasksClient.Update":
				res.resp, res.err = t.dispatchUpdate(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 (t *TasksServerTransport) dispatchCancel(req *http.Request) (*http.Response, error) {
	if t.srv.Cancel == nil {
		return nil, &nonRetriableError{errors.New("fake for method Cancel not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<groupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DataMigration/services/(?P<serviceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P<projectName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tasks/(?P<taskName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/cancel`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 6 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	groupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("groupName")])
	if err != nil {
		return nil, err
	}
	serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")])
	if err != nil {
		return nil, err
	}
	projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")])
	if err != nil {
		return nil, err
	}
	taskNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("taskName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := t.srv.Cancel(req.Context(), groupNameParam, serviceNameParam, projectNameParam, taskNameParam, 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).ProjectTask, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (t *TasksServerTransport) dispatchCommand(req *http.Request) (*http.Response, error) {
	if t.srv.Command == nil {
		return nil, &nonRetriableError{errors.New("fake for method Command not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<groupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DataMigration/services/(?P<serviceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P<projectName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tasks/(?P<taskName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/command`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 6 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	raw, err := readRequestBody(req)
	if err != nil {
		return nil, err
	}
	body, err := unmarshalCommandPropertiesClassification(raw)
	if err != nil {
		return nil, err
	}
	groupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("groupName")])
	if err != nil {
		return nil, err
	}
	serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")])
	if err != nil {
		return nil, err
	}
	projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")])
	if err != nil {
		return nil, err
	}
	taskNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("taskName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := t.srv.Command(req.Context(), groupNameParam, serviceNameParam, projectNameParam, taskNameParam, body, 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).CommandPropertiesClassification, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (t *TasksServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) {
	if t.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<groupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DataMigration/services/(?P<serviceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P<projectName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tasks/(?P<taskName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 6 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armdatamigration.ProjectTask](req)
	if err != nil {
		return nil, err
	}
	groupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("groupName")])
	if err != nil {
		return nil, err
	}
	serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")])
	if err != nil {
		return nil, err
	}
	projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")])
	if err != nil {
		return nil, err
	}
	taskNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("taskName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := t.srv.CreateOrUpdate(req.Context(), groupNameParam, serviceNameParam, projectNameParam, taskNameParam, 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).ProjectTask, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (t *TasksServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) {
	if t.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<groupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DataMigration/services/(?P<serviceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P<projectName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tasks/(?P<taskName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 6 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	qp := req.URL.Query()
	groupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("groupName")])
	if err != nil {
		return nil, err
	}
	serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")])
	if err != nil {
		return nil, err
	}
	projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")])
	if err != nil {
		return nil, err
	}
	taskNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("taskName")])
	if err != nil {
		return nil, err
	}
	deleteRunningTasksUnescaped, err := url.QueryUnescape(qp.Get("deleteRunningTasks"))
	if err != nil {
		return nil, err
	}
	deleteRunningTasksParam, err := parseOptional(deleteRunningTasksUnescaped, strconv.ParseBool)
	if err != nil {
		return nil, err
	}
	var options *armdatamigration.TasksClientDeleteOptions
	if deleteRunningTasksParam != nil {
		options = &armdatamigration.TasksClientDeleteOptions{
			DeleteRunningTasks: deleteRunningTasksParam,
		}
	}
	respr, errRespr := t.srv.Delete(req.Context(), groupNameParam, serviceNameParam, projectNameParam, taskNameParam, options)
	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 (t *TasksServerTransport) dispatchGet(req *http.Request) (*http.Response, error) {
	if t.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<groupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DataMigration/services/(?P<serviceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P<projectName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tasks/(?P<taskName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 6 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	qp := req.URL.Query()
	groupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("groupName")])
	if err != nil {
		return nil, err
	}
	serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")])
	if err != nil {
		return nil, err
	}
	projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")])
	if err != nil {
		return nil, err
	}
	taskNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("taskName")])
	if err != nil {
		return nil, err
	}
	expandUnescaped, err := url.QueryUnescape(qp.Get("$expand"))
	if err != nil {
		return nil, err
	}
	expandParam := getOptional(expandUnescaped)
	var options *armdatamigration.TasksClientGetOptions
	if expandParam != nil {
		options = &armdatamigration.TasksClientGetOptions{
			Expand: expandParam,
		}
	}
	respr, errRespr := t.srv.Get(req.Context(), groupNameParam, serviceNameParam, projectNameParam, taskNameParam, 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).ProjectTask, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func (t *TasksServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) {
	if t.srv.NewListPager == nil {
		return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")}
	}
	newListPager := t.newListPager.get(req)
	if newListPager == nil {
		const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<groupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DataMigration/services/(?P<serviceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P<projectName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tasks`
		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)
		}
		qp := req.URL.Query()
		groupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("groupName")])
		if err != nil {
			return nil, err
		}
		serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")])
		if err != nil {
			return nil, err
		}
		projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")])
		if err != nil {
			return nil, err
		}
		taskTypeUnescaped, err := url.QueryUnescape(qp.Get("taskType"))
		if err != nil {
			return nil, err
		}
		taskTypeParam := getOptional(taskTypeUnescaped)
		var options *armdatamigration.TasksClientListOptions
		if taskTypeParam != nil {
			options = &armdatamigration.TasksClientListOptions{
				TaskType: taskTypeParam,
			}
		}
		resp := t.srv.NewListPager(groupNameParam, serviceNameParam, projectNameParam, options)
		newListPager = &resp
		t.newListPager.add(req, newListPager)
		server.PagerResponderInjectNextLinks(newListPager, req, func(page *armdatamigration.TasksClientListResponse, 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) {
		t.newListPager.remove(req)
		return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)}
	}
	if !server.PagerResponderMore(newListPager) {
		t.newListPager.remove(req)
	}
	return resp, nil
}

func (t *TasksServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) {
	if t.srv.Update == nil {
		return nil, &nonRetriableError{errors.New("fake for method Update not implemented")}
	}
	const regexStr = `/subscriptions/(?P<subscriptionId>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P<groupName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DataMigration/services/(?P<serviceName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P<projectName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/tasks/(?P<taskName>[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)`
	regex := regexp.MustCompile(regexStr)
	matches := regex.FindStringSubmatch(req.URL.EscapedPath())
	if len(matches) < 6 {
		return nil, fmt.Errorf("failed to parse path %s", req.URL.Path)
	}
	body, err := server.UnmarshalRequestAsJSON[armdatamigration.ProjectTask](req)
	if err != nil {
		return nil, err
	}
	groupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("groupName")])
	if err != nil {
		return nil, err
	}
	serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")])
	if err != nil {
		return nil, err
	}
	projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")])
	if err != nil {
		return nil, err
	}
	taskNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("taskName")])
	if err != nil {
		return nil, err
	}
	respr, errRespr := t.srv.Update(req.Context(), groupNameParam, serviceNameParam, projectNameParam, taskNameParam, body, 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).ProjectTask, req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

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