//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 armiotsecurity

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// DeviceGroupsClient contains the methods for the DeviceGroups group.
// Don't use this type directly, use NewDeviceGroupsClient() instead.
type DeviceGroupsClient struct {
	internal       *arm.Client
	subscriptionID string
}

// NewDeviceGroupsClient creates a new instance of DeviceGroupsClient with the specified values.
//   - subscriptionID - The ID of the target subscription.
//   - credential - used to authorize requests. Usually a credential from azidentity.
//   - options - pass nil to accept the default values.
func NewDeviceGroupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DeviceGroupsClient, error) {
	cl, err := arm.NewClient(moduleName, moduleVersion, credential, options)
	if err != nil {
		return nil, err
	}
	client := &DeviceGroupsClient{
		subscriptionID: subscriptionID,
		internal:       cl,
	}
	return client, nil
}

// CreateOrUpdate - Create or update device group
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2021-02-01-preview
//   - iotDefenderLocation - Defender for IoT location
//   - deviceGroupName - Device group name
//   - deviceGroupModel - Device group model
//   - options - DeviceGroupsClientCreateOrUpdateOptions contains the optional parameters for the DeviceGroupsClient.CreateOrUpdate
//     method.
func (client *DeviceGroupsClient) CreateOrUpdate(ctx context.Context, iotDefenderLocation string, deviceGroupName string, deviceGroupModel DeviceGroupModel, options *DeviceGroupsClientCreateOrUpdateOptions) (DeviceGroupsClientCreateOrUpdateResponse, error) {
	var err error
	const operationName = "DeviceGroupsClient.CreateOrUpdate"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.createOrUpdateCreateRequest(ctx, iotDefenderLocation, deviceGroupName, deviceGroupModel, options)
	if err != nil {
		return DeviceGroupsClientCreateOrUpdateResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return DeviceGroupsClientCreateOrUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) {
		err = runtime.NewResponseError(httpResp)
		return DeviceGroupsClientCreateOrUpdateResponse{}, err
	}
	resp, err := client.createOrUpdateHandleResponse(httpResp)
	return resp, err
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *DeviceGroupsClient) createOrUpdateCreateRequest(ctx context.Context, iotDefenderLocation string, deviceGroupName string, deviceGroupModel DeviceGroupModel, options *DeviceGroupsClientCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.IoTSecurity/locations/{iotDefenderLocation}/deviceGroups/{deviceGroupName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if iotDefenderLocation == "" {
		return nil, errors.New("parameter iotDefenderLocation cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{iotDefenderLocation}", url.PathEscape(iotDefenderLocation))
	if deviceGroupName == "" {
		return nil, errors.New("parameter deviceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{deviceGroupName}", url.PathEscape(deviceGroupName))
	req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-02-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	if err := runtime.MarshalAsJSON(req, deviceGroupModel); err != nil {
		return nil, err
	}
	return req, nil
}

// createOrUpdateHandleResponse handles the CreateOrUpdate response.
func (client *DeviceGroupsClient) createOrUpdateHandleResponse(resp *http.Response) (DeviceGroupsClientCreateOrUpdateResponse, error) {
	result := DeviceGroupsClientCreateOrUpdateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.DeviceGroupModel); err != nil {
		return DeviceGroupsClientCreateOrUpdateResponse{}, err
	}
	return result, nil
}

// Delete - Delete device group
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2021-02-01-preview
//   - iotDefenderLocation - Defender for IoT location
//   - deviceGroupName - Device group name
//   - options - DeviceGroupsClientDeleteOptions contains the optional parameters for the DeviceGroupsClient.Delete method.
func (client *DeviceGroupsClient) Delete(ctx context.Context, iotDefenderLocation string, deviceGroupName string, options *DeviceGroupsClientDeleteOptions) (DeviceGroupsClientDeleteResponse, error) {
	var err error
	const operationName = "DeviceGroupsClient.Delete"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.deleteCreateRequest(ctx, iotDefenderLocation, deviceGroupName, options)
	if err != nil {
		return DeviceGroupsClientDeleteResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return DeviceGroupsClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) {
		err = runtime.NewResponseError(httpResp)
		return DeviceGroupsClientDeleteResponse{}, err
	}
	return DeviceGroupsClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *DeviceGroupsClient) deleteCreateRequest(ctx context.Context, iotDefenderLocation string, deviceGroupName string, options *DeviceGroupsClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.IoTSecurity/locations/{iotDefenderLocation}/deviceGroups/{deviceGroupName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if iotDefenderLocation == "" {
		return nil, errors.New("parameter iotDefenderLocation cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{iotDefenderLocation}", url.PathEscape(iotDefenderLocation))
	if deviceGroupName == "" {
		return nil, errors.New("parameter deviceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{deviceGroupName}", url.PathEscape(deviceGroupName))
	req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-02-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Get device group
// If the operation fails it returns an *azcore.ResponseError type.
//
// Generated from API version 2021-02-01-preview
//   - iotDefenderLocation - Defender for IoT location
//   - deviceGroupName - Device group name
//   - options - DeviceGroupsClientGetOptions contains the optional parameters for the DeviceGroupsClient.Get method.
func (client *DeviceGroupsClient) Get(ctx context.Context, iotDefenderLocation string, deviceGroupName string, options *DeviceGroupsClientGetOptions) (DeviceGroupsClientGetResponse, error) {
	var err error
	const operationName = "DeviceGroupsClient.Get"
	ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName)
	ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil)
	defer func() { endSpan(err) }()
	req, err := client.getCreateRequest(ctx, iotDefenderLocation, deviceGroupName, options)
	if err != nil {
		return DeviceGroupsClientGetResponse{}, err
	}
	httpResp, err := client.internal.Pipeline().Do(req)
	if err != nil {
		return DeviceGroupsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(httpResp, http.StatusOK) {
		err = runtime.NewResponseError(httpResp)
		return DeviceGroupsClientGetResponse{}, err
	}
	resp, err := client.getHandleResponse(httpResp)
	return resp, err
}

// getCreateRequest creates the Get request.
func (client *DeviceGroupsClient) getCreateRequest(ctx context.Context, iotDefenderLocation string, deviceGroupName string, options *DeviceGroupsClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.IoTSecurity/locations/{iotDefenderLocation}/deviceGroups/{deviceGroupName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if iotDefenderLocation == "" {
		return nil, errors.New("parameter iotDefenderLocation cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{iotDefenderLocation}", url.PathEscape(iotDefenderLocation))
	if deviceGroupName == "" {
		return nil, errors.New("parameter deviceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{deviceGroupName}", url.PathEscape(deviceGroupName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-02-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *DeviceGroupsClient) getHandleResponse(resp *http.Response) (DeviceGroupsClientGetResponse, error) {
	result := DeviceGroupsClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.DeviceGroupModel); err != nil {
		return DeviceGroupsClientGetResponse{}, err
	}
	return result, nil
}

// NewListPager - List device groups
//
// Generated from API version 2021-02-01-preview
//   - iotDefenderLocation - Defender for IoT location
//   - options - DeviceGroupsClientListOptions contains the optional parameters for the DeviceGroupsClient.NewListPager method.
func (client *DeviceGroupsClient) NewListPager(iotDefenderLocation string, options *DeviceGroupsClientListOptions) *runtime.Pager[DeviceGroupsClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[DeviceGroupsClientListResponse]{
		More: func(page DeviceGroupsClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *DeviceGroupsClientListResponse) (DeviceGroupsClientListResponse, error) {
			ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DeviceGroupsClient.NewListPager")
			nextLink := ""
			if page != nil {
				nextLink = *page.NextLink
			}
			resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) {
				return client.listCreateRequest(ctx, iotDefenderLocation, options)
			}, nil)
			if err != nil {
				return DeviceGroupsClientListResponse{}, err
			}
			return client.listHandleResponse(resp)
		},
		Tracer: client.internal.Tracer(),
	})
}

// listCreateRequest creates the List request.
func (client *DeviceGroupsClient) listCreateRequest(ctx context.Context, iotDefenderLocation string, options *DeviceGroupsClientListOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.IoTSecurity/locations/{iotDefenderLocation}/deviceGroups"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if iotDefenderLocation == "" {
		return nil, errors.New("parameter iotDefenderLocation cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{iotDefenderLocation}", url.PathEscape(iotDefenderLocation))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-02-01-preview")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listHandleResponse handles the List response.
func (client *DeviceGroupsClient) listHandleResponse(resp *http.Response) (DeviceGroupsClientListResponse, error) {
	result := DeviceGroupsClientListResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.DeviceGroupList); err != nil {
		return DeviceGroupsClientListResponse{}, err
	}
	return result, nil
}
