// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation

// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length

/// User-configurable options for the `StringNull` operation.
public struct StringNullOptions: RequestOptions {
    /// null string value
    public let stringQuery: String?

    /// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    /// Highly recommended for correlating client-side activites with requests received by the server.
    public let clientRequestId: String?

    /// A token used to make a best-effort attempt at canceling a request.
    public let cancellationToken: CancellationToken?

    /// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    public var dispatchQueue: DispatchQueue?

    /// A `PipelineContext` object to associate with the request.
    public var context: PipelineContext?

    /// Initialize a `StringNullOptions` structure.
    /// - Parameters:
    ///   - stringQuery: null string value
    ///   - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    ///   - cancellationToken: A token used to make a best-effort attempt at canceling a request.
    ///   - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    ///   - context: A `PipelineContext` object to associate with the request.
    public init(
        stringQuery: String? = nil,
        clientRequestId: String? = nil,
        cancellationToken: CancellationToken? = nil,
        dispatchQueue: DispatchQueue? = nil,
        context: PipelineContext? = nil
    ) {
        self.stringQuery = stringQuery
        self.clientRequestId = clientRequestId
        self.cancellationToken = cancellationToken
        self.dispatchQueue = dispatchQueue
        self.context = context
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation

// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length

/// User-configurable options for the `StringUnicode` operation.
public struct StringUnicodeOptions: RequestOptions {
    /// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    /// Highly recommended for correlating client-side activites with requests received by the server.
    public let clientRequestId: String?

    /// A token used to make a best-effort attempt at canceling a request.
    public let cancellationToken: CancellationToken?

    /// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    public var dispatchQueue: DispatchQueue?

    /// A `PipelineContext` object to associate with the request.
    public var context: PipelineContext?

    /// Initialize a `StringUnicodeOptions` structure.
    /// - Parameters:
    ///   - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    ///   - cancellationToken: A token used to make a best-effort attempt at canceling a request.
    ///   - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    ///   - context: A `PipelineContext` object to associate with the request.
    public init(
        clientRequestId: String? = nil,
        cancellationToken: CancellationToken? = nil,
        dispatchQueue: DispatchQueue? = nil,
        context: PipelineContext? = nil
    ) {
        self.clientRequestId = clientRequestId
        self.cancellationToken = cancellationToken
        self.dispatchQueue = dispatchQueue
        self.context = context
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation

// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length

/// User-configurable options for the `StringUrlEncoded` operation.
public struct StringUrlEncodedOptions: RequestOptions {
    /// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    /// Highly recommended for correlating client-side activites with requests received by the server.
    public let clientRequestId: String?

    /// A token used to make a best-effort attempt at canceling a request.
    public let cancellationToken: CancellationToken?

    /// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    public var dispatchQueue: DispatchQueue?

    /// A `PipelineContext` object to associate with the request.
    public var context: PipelineContext?

    /// Initialize a `StringUrlEncodedOptions` structure.
    /// - Parameters:
    ///   - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    ///   - cancellationToken: A token used to make a best-effort attempt at canceling a request.
    ///   - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    ///   - context: A `PipelineContext` object to associate with the request.
    public init(
        clientRequestId: String? = nil,
        cancellationToken: CancellationToken? = nil,
        dispatchQueue: DispatchQueue? = nil,
        context: PipelineContext? = nil
    ) {
        self.clientRequestId = clientRequestId
        self.cancellationToken = cancellationToken
        self.dispatchQueue = dispatchQueue
        self.context = context
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation

// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length

/// User-configurable options for the `StringUrlNonEncoded` operation.
public struct StringUrlNonEncodedOptions: RequestOptions {
    /// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    /// Highly recommended for correlating client-side activites with requests received by the server.
    public let clientRequestId: String?

    /// A token used to make a best-effort attempt at canceling a request.
    public let cancellationToken: CancellationToken?

    /// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    public var dispatchQueue: DispatchQueue?

    /// A `PipelineContext` object to associate with the request.
    public var context: PipelineContext?

    /// Initialize a `StringUrlNonEncodedOptions` structure.
    /// - Parameters:
    ///   - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    ///   - cancellationToken: A token used to make a best-effort attempt at canceling a request.
    ///   - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    ///   - context: A `PipelineContext` object to associate with the request.
    public init(
        clientRequestId: String? = nil,
        cancellationToken: CancellationToken? = nil,
        dispatchQueue: DispatchQueue? = nil,
        context: PipelineContext? = nil
    ) {
        self.clientRequestId = clientRequestId
        self.cancellationToken = cancellationToken
        self.dispatchQueue = dispatchQueue
        self.context = context
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation

// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length

/// User-configurable options for the `UnixTimeUrl` operation.
public struct UnixTimeUrlOptions: RequestOptions {
    /// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    /// Highly recommended for correlating client-side activites with requests received by the server.
    public let clientRequestId: String?

    /// A token used to make a best-effort attempt at canceling a request.
    public let cancellationToken: CancellationToken?

    /// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    public var dispatchQueue: DispatchQueue?

    /// A `PipelineContext` object to associate with the request.
    public var context: PipelineContext?

    /// Initialize a `UnixTimeUrlOptions` structure.
    /// - Parameters:
    ///   - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    ///   - cancellationToken: A token used to make a best-effort attempt at canceling a request.
    ///   - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    ///   - context: A `PipelineContext` object to associate with the request.
    public init(
        clientRequestId: String? = nil,
        cancellationToken: CancellationToken? = nil,
        dispatchQueue: DispatchQueue? = nil,
        context: PipelineContext? = nil
    ) {
        self.clientRequestId = clientRequestId
        self.cancellationToken = cancellationToken
        self.dispatchQueue = dispatchQueue
        self.context = context
    }
}


import Foundation

// TODO: Remove this when these objects are in AzureCore

enum MergePatchOpType: String, Codable {
    case add
    case remove
    case replace
    case move
    case copy
    case test
}

// TODO: NO support for nil-setting sentinel

struct MergePatchOperation: Encodable {
    let operation: MergePatchOpType
    let from: String?
    let path: String
    let value: String?

    // MARK: Encodable

    enum CodingKeys: String, CodingKey {
        case operation, from, path, value
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(operation, forKey: .operation)
        try container.encode(from, forKey: .from)
        try container.encode(path, forKey: .path)
        try container.encode(value, forKey: .value)
    }
}

/// Helper class for creating PatchObjects
final class MergePatchObject: Encodable {
    fileprivate var operations = [MergePatchOperation]()

    /// Inserts a new value at an array index or adds a new property.
    func add(atPath path: String, withValue value: String) {
        operations.append(MergePatchOperation(operation: .add, from: nil, path: path, value: value))
    }

    /// Remove the property or entry at an array index. Property must exist.
    func remove(atPath path: String) {
        operations.append(MergePatchOperation(operation: .remove, from: nil, path: path, value: nil))
    }

    /// Replaces the value at the target location with a new value. Existing value must exist.
    func replace(atPath path: String, withValue value: String) {
        operations.append(MergePatchOperation(operation: .replace, from: nil, path: path, value: value))
    }

    /// Remove the value at a specified location and adds it to the target location.
    func move(fromPath src: String, toPath dest: String) {
        operations.append(MergePatchOperation(operation: .move, from: src, path: dest, value: nil))
    }

    /// Copies the value at a specified location and adds it to the target location.
    func copy(fromPath src: String, toPath dest: String) {
        operations.append(MergePatchOperation(operation: .copy, from: src, path: dest, value: nil))
    }

    /// Tests that a value at the target location is equal to a specified value.
    func test(atPath path: String, equalsValue value: String) {
        operations.append(MergePatchOperation(operation: .test, from: nil, path: path, value: value))
    }
}


// swift-tools-version:5.1
//  The swift-tools-version declares the minimum version of Swift required to build this package.
//
// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import PackageDescription

let package = Package(
    name: "AutoRestUrlMutliCollectionFormatTest",
    platforms: [
        .macOS(.v10_15), .iOS(.v12), .tvOS(.v12)
    ],
    products: [
        .library(
            name: "AutoRestUrlMutliCollectionFormatTest",
            type: .static,
            targets: ["AutoRestUrlMutliCollectionFormatTest"]
        )
    ],
    dependencies: [
        .package(
            url: "https://github.com/Azure/SwiftPM-AzureCore.git",
            .branch("dev/AzureCore")
        )
    ],
    targets: [
        // Build targets
        .target(
            name: "AutoRestUrlMutliCollectionFormatTest",
            dependencies: ["AzureCore"],
            path: "Source"
        )
    ],
    swiftLanguageVersions: [.v5]
)


// --------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the ""Software""), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
// --------------------------------------------------------------------------

import Foundation

// TODO: Custom Code Here


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// swiftlint:disable cyclomatic_complexity
// swiftlint:disable function_body_length
// swiftlint:disable type_body_length

public final class AutoRestUrlMutliCollectionFormatTestClient: PipelineClient {
    /// Options provided to configure this `AutoRestUrlMutliCollectionFormatTestClient`.
    public let options: AutoRestUrlMutliCollectionFormatTestClientOptions

    // MARK: Initializers

    /// Create a AutoRestUrlMutliCollectionFormatTestClient client.
    /// - Parameters:
    ///   - endpoint: Base URL for the AutoRestUrlMutliCollectionFormatTestClient.
    ///   - authPolicy: An `Authenticating` policy to use for authenticating client requests.
    ///   - options: Options used to configure the client.
    public init(
        url: URL? = nil,
        authPolicy: Authenticating,
        withOptions options: AutoRestUrlMutliCollectionFormatTestClientOptions
    ) throws {
        let defaultHost = URL(string: "http://localhost:3000")
        guard let endpoint = url ?? defaultHost else {
            fatalError("Unable to determine base URL. ")
        }
        self.options = options
        super.init(
            endpoint: endpoint,
            transport: options.transportOptions.transport ?? URLSessionTransport(),
            policies: [
                UserAgentPolicy(
                    for: AutoRestUrlMutliCollectionFormatTestClient.self,
                    telemetryOptions: options.telemetryOptions
                ),
                RequestIdPolicy(),
                AddDatePolicy(),
                authPolicy,
                ContentDecodePolicy(),
                LoggingPolicy(),
                NormalizeETagPolicy()
            ],
            logger: options.logger,
            options: options
        )
    }

    public lazy var queries = Queries(client: self)

    // MARK: Client Methods
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// swiftlint:disable cyclomatic_complexity
// swiftlint:disable function_body_length
// swiftlint:disable type_body_length

public final class Queries {
    public let client: AutoRestUrlMutliCollectionFormatTestClient

    init(client: AutoRestUrlMutliCollectionFormatTestClient) {
        self.client = client
    }

    /// Get a null array of string using the multi-array format
    /// - Parameters:

    ///    - options: A list of options for the operation
    ///    - completionHandler: A completion handler that receives a status code on
    ///     success.
    public func arrayStringMultiNull(
        withOptions options: ArrayStringMultiNullOptions? = nil,
        completionHandler: @escaping HTTPResultHandler<Void>
    ) {
        let dispatchQueue = options?.dispatchQueue ?? client.commonOptions.dispatchQueue ?? DispatchQueue.main

        // Create request parameters
        var params = RequestParameters(
            (.uri, "$host", client.endpoint.absoluteString, .skipEncoding),
            (.header, "Accept", "application/json", .encode)
        )
        // Explode query parameters
        options?.arrayQuery?.forEach {
            params.add((.query, "arrayQuery", $0, .encode))
        }

        // Construct request
        let urlTemplate = "/queries/array/multi/string/null"
        guard let requestUrl = client.url(host: "{$host}", template: urlTemplate, params: params),
            let request = try? HTTPRequest(method: .get, url: requestUrl, headers: params.headers)
        else {
            client.options.logger.error("Failed to construct HTTP request.")
            return
        }

        // Send request
        let context = PipelineContext.of(keyValues: [
            ContextKey.allowedStatusCodes.rawValue: [200] as AnyObject
        ])
        context.add(cancellationToken: options?.cancellationToken, applying: client.options)
        context.merge(with: options?.context)
        client.request(request, context: context) { result, httpResponse in
            guard let data = httpResponse?.data else {
                let noDataError = AzureError.client("Response data expected but not found.")
                dispatchQueue.async {
                    completionHandler(.failure(noDataError), httpResponse)
                }
                return
            }
            switch result {
            case .success:
                guard let statusCode = httpResponse?.statusCode else {
                    let noStatusCodeError = AzureError.client("Expected a status code in response but didn't find one.")
                    dispatchQueue.async {
                        completionHandler(.failure(noStatusCodeError), httpResponse)
                    }
                    return
                }
                if [
                    200
                ].contains(statusCode) {
                    dispatchQueue.async {
                        completionHandler(
                            .success(()),
                            httpResponse
                        )
                    }
                }
            case .failure:
                do {
                    let decoder = JSONDecoder()
                    let decoded = try decoder.decode(ErrorType.self, from: data)
                    dispatchQueue.async {
                        completionHandler(.failure(AzureError.service("Unexpected error", decoded)), httpResponse)
                    }
                } catch {
                    dispatchQueue.async {
                        completionHandler(.failure(AzureError.client("Decoding error.", error)), httpResponse)
                    }
                }
            }
        }
    }

    /// Get an empty array [] of string using the multi-array format
    /// - Parameters:

    ///    - options: A list of options for the operation
    ///    - completionHandler: A completion handler that receives a status code on
    ///     success.
    public func arrayStringMultiEmpty(
        withOptions options: ArrayStringMultiEmptyOptions? = nil,
        completionHandler: @escaping HTTPResultHandler<Void>
    ) {
        let dispatchQueue = options?.dispatchQueue ?? client.commonOptions.dispatchQueue ?? DispatchQueue.main

        // Create request parameters
        var params = RequestParameters(
            (.uri, "$host", client.endpoint.absoluteString, .skipEncoding),
            (.header, "Accept", "application/json", .encode)
        )
        // Explode query parameters
        options?.arrayQuery?.forEach {
            params.add((.query, "arrayQuery", $0, .encode))
        }

        // Construct request
        let urlTemplate = "/queries/array/multi/string/empty"
        guard let requestUrl = client.url(host: "{$host}", template: urlTemplate, params: params),
            let request = try? HTTPRequest(method: .get, url: requestUrl, headers: params.headers)
        else {
            client.options.logger.error("Failed to construct HTTP request.")
            return
        }

        // Send request
        let context = PipelineContext.of(keyValues: [
            ContextKey.allowedStatusCodes.rawValue: [200] as AnyObject
        ])
        context.add(cancellationToken: options?.cancellationToken, applying: client.options)
        context.merge(with: options?.context)
        client.request(request, context: context) { result, httpResponse in
            guard let data = httpResponse?.data else {
                let noDataError = AzureError.client("Response data expected but not found.")
                dispatchQueue.async {
                    completionHandler(.failure(noDataError), httpResponse)
                }
                return
            }
            switch result {
            case .success:
                guard let statusCode = httpResponse?.statusCode else {
                    let noStatusCodeError = AzureError.client("Expected a status code in response but didn't find one.")
                    dispatchQueue.async {
                        completionHandler(.failure(noStatusCodeError), httpResponse)
                    }
                    return
                }
                if [
                    200
                ].contains(statusCode) {
                    dispatchQueue.async {
                        completionHandler(
                            .success(()),
                            httpResponse
                        )
                    }
                }
            case .failure:
                do {
                    let decoder = JSONDecoder()
                    let decoded = try decoder.decode(ErrorType.self, from: data)
                    dispatchQueue.async {
                        completionHandler(.failure(AzureError.service("Unexpected error", decoded)), httpResponse)
                    }
                } catch {
                    dispatchQueue.async {
                        completionHandler(.failure(AzureError.client("Decoding error.", error)), httpResponse)
                    }
                }
            }
        }
    }

    /// Get an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the mult-array format
    /// - Parameters:

    ///    - options: A list of options for the operation
    ///    - completionHandler: A completion handler that receives a status code on
    ///     success.
    public func arrayStringMultiValid(
        withOptions options: ArrayStringMultiValidOptions? = nil,
        completionHandler: @escaping HTTPResultHandler<Void>
    ) {
        let dispatchQueue = options?.dispatchQueue ?? client.commonOptions.dispatchQueue ?? DispatchQueue.main

        // Create request parameters
        var params = RequestParameters(
            (.uri, "$host", client.endpoint.absoluteString, .skipEncoding),
            (.header, "Accept", "application/json", .encode)
        )
        // Explode query parameters
        options?.arrayQuery?.forEach {
            params.add((.query, "arrayQuery", $0, .encode))
        }

        // Construct request
        let urlTemplate = "/queries/array/multi/string/valid"
        guard let requestUrl = client.url(host: "{$host}", template: urlTemplate, params: params),
            let request = try? HTTPRequest(method: .get, url: requestUrl, headers: params.headers)
        else {
            client.options.logger.error("Failed to construct HTTP request.")
            return
        }

        // Send request
        let context = PipelineContext.of(keyValues: [
            ContextKey.allowedStatusCodes.rawValue: [200] as AnyObject
        ])
        context.add(cancellationToken: options?.cancellationToken, applying: client.options)
        context.merge(with: options?.context)
        client.request(request, context: context) { result, httpResponse in
            guard let data = httpResponse?.data else {
                let noDataError = AzureError.client("Response data expected but not found.")
                dispatchQueue.async {
                    completionHandler(.failure(noDataError), httpResponse)
                }
                return
            }
            switch result {
            case .success:
                guard let statusCode = httpResponse?.statusCode else {
                    let noStatusCodeError = AzureError.client("Expected a status code in response but didn't find one.")
                    dispatchQueue.async {
                        completionHandler(.failure(noStatusCodeError), httpResponse)
                    }
                    return
                }
                if [
                    200
                ].contains(statusCode) {
                    dispatchQueue.async {
                        completionHandler(
                            .success(()),
                            httpResponse
                        )
                    }
                }
            case .failure:
                do {
                    let decoder = JSONDecoder()
                    let decoded = try decoder.decode(ErrorType.self, from: data)
                    dispatchQueue.async {
                        completionHandler(.failure(AzureError.service("Unexpected error", decoded)), httpResponse)
                    }
                } catch {
                    dispatchQueue.async {
                        completionHandler(.failure(AzureError.client("Decoding error.", error)), httpResponse)
                    }
                }
            }
        }
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length
// swiftlint:disable cyclomatic_complexity

public struct ErrorType: Codable, Swift.Error {
    // MARK: Properties

    public let status: Int32?

    public let message: String?

    // MARK: Initializers

    /// Initialize a `ErrorType` structure.
    /// - Parameters:
    ///   - status:
    ///   - message:
    public init(
        status: Int32? = nil, message: String? = nil
    ) {
        self.status = status
        self.message = message
    }

    // MARK: Codable

    enum CodingKeys: String, CodingKey {
        case status = "status"
        case message = "message"
    }

    /// Initialize a `ErrorType` structure from decoder
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.status = try? container.decode(Int32.self, forKey: .status)
        self.message = try? container.decode(String.self, forKey: .message)
    }

    /// Encode a `ErrorType` structure
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        if status != nil { try? container.encode(status, forKey: .status) }
        if message != nil { try? container.encode(message, forKey: .message) }
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation

// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length

/// User-configurable options for the `ArrayStringMultiEmpty` operation.
public struct ArrayStringMultiEmptyOptions: RequestOptions {
    /// an empty array [] of string using the multi-array format
    public let arrayQuery: [String]?

    /// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    /// Highly recommended for correlating client-side activites with requests received by the server.
    public let clientRequestId: String?

    /// A token used to make a best-effort attempt at canceling a request.
    public let cancellationToken: CancellationToken?

    /// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    public var dispatchQueue: DispatchQueue?

    /// A `PipelineContext` object to associate with the request.
    public var context: PipelineContext?

    /// Initialize a `ArrayStringMultiEmptyOptions` structure.
    /// - Parameters:
    ///   - arrayQuery: an empty array [] of string using the multi-array format
    ///   - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    ///   - cancellationToken: A token used to make a best-effort attempt at canceling a request.
    ///   - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    ///   - context: A `PipelineContext` object to associate with the request.
    public init(
        arrayQuery: [String]? = nil,
        clientRequestId: String? = nil,
        cancellationToken: CancellationToken? = nil,
        dispatchQueue: DispatchQueue? = nil,
        context: PipelineContext? = nil
    ) {
        self.arrayQuery = arrayQuery
        self.clientRequestId = clientRequestId
        self.cancellationToken = cancellationToken
        self.dispatchQueue = dispatchQueue
        self.context = context
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation

// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length

/// User-configurable options for the `ArrayStringMultiNull` operation.
public struct ArrayStringMultiNullOptions: RequestOptions {
    /// a null array of string using the multi-array format
    public let arrayQuery: [String]?

    /// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    /// Highly recommended for correlating client-side activites with requests received by the server.
    public let clientRequestId: String?

    /// A token used to make a best-effort attempt at canceling a request.
    public let cancellationToken: CancellationToken?

    /// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    public var dispatchQueue: DispatchQueue?

    /// A `PipelineContext` object to associate with the request.
    public var context: PipelineContext?

    /// Initialize a `ArrayStringMultiNullOptions` structure.
    /// - Parameters:
    ///   - arrayQuery: a null array of string using the multi-array format
    ///   - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    ///   - cancellationToken: A token used to make a best-effort attempt at canceling a request.
    ///   - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    ///   - context: A `PipelineContext` object to associate with the request.
    public init(
        arrayQuery: [String]? = nil,
        clientRequestId: String? = nil,
        cancellationToken: CancellationToken? = nil,
        dispatchQueue: DispatchQueue? = nil,
        context: PipelineContext? = nil
    ) {
        self.arrayQuery = arrayQuery
        self.clientRequestId = clientRequestId
        self.cancellationToken = cancellationToken
        self.dispatchQueue = dispatchQueue
        self.context = context
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation

// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length

/// User-configurable options for the `ArrayStringMultiValid` operation.
public struct ArrayStringMultiValidOptions: RequestOptions {
    /// an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the mult-array format
    public let arrayQuery: [String?]?

    /// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    /// Highly recommended for correlating client-side activites with requests received by the server.
    public let clientRequestId: String?

    /// A token used to make a best-effort attempt at canceling a request.
    public let cancellationToken: CancellationToken?

    /// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    public var dispatchQueue: DispatchQueue?

    /// A `PipelineContext` object to associate with the request.
    public var context: PipelineContext?

    /// Initialize a `ArrayStringMultiValidOptions` structure.
    /// - Parameters:
    ///   - arrayQuery: an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the mult-array format
    ///   - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    ///   - cancellationToken: A token used to make a best-effort attempt at canceling a request.
    ///   - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    ///   - context: A `PipelineContext` object to associate with the request.
    public init(
        arrayQuery: [String?]? = nil,
        clientRequestId: String? = nil,
        cancellationToken: CancellationToken? = nil,
        dispatchQueue: DispatchQueue? = nil,
        context: PipelineContext? = nil
    ) {
        self.arrayQuery = arrayQuery
        self.clientRequestId = clientRequestId
        self.cancellationToken = cancellationToken
        self.dispatchQueue = dispatchQueue
        self.context = context
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length

/// User-configurable client options.
public struct AutoRestUrlMutliCollectionFormatTestClientOptions: ClientOptions {
    /// The API version of the client to invoke.
    public let apiVersion: String
    /// The `ClientLogger` to be used by this client.
    public let logger: ClientLogger
    /// Options for configuring telemetry sent by this client.
    public let telemetryOptions: TelemetryOptions
    /// Global transport options
    public let transportOptions: TransportOptions
    /// The default dispatch queue on which to call all completion handler. Defaults to `DispatchQueue.main`.
    public let dispatchQueue: DispatchQueue?

    /// API version of the  to invoke. Defaults to the latest.
    public enum ApiVersion: RequestStringConvertible {
        /// Custom value for unrecognized enum values
        case custom(String)
        /// API version ""
        case v

        /// The most recent API version of the
        public static var latest: ApiVersion {
            return .v
        }

        public var requestString: String {
            switch self {
            case let .custom(val):
                return val
            case .v:
                return ""
            }
        }

        public init(_ val: String) {
            switch val.lowercased() {
            case "":
                self = .v
            default:
                self = .custom(val)
            }
        }
    }

    /// Initialize a `AutoRestUrlMutliCollectionFormatTestClientOptions` structure.
    /// - Parameters:
    ///   - apiVersion: The API version of the client to invoke.
    ///   - logger: The `ClientLogger` to be used by this client.
    ///   - telemetryOptions: Options for configuring telemetry sent by this client.
    ///   - cancellationToken: A token used to make a best-effort attempt at canceling a request.
    ///   - dispatchQueue: The default dispatch queue on which to call all completion handler. Defaults to `DispatchQueue.main`.
    public init(
        apiVersion: AutoRestUrlMutliCollectionFormatTestClientOptions.ApiVersion = .latest,
        logger: ClientLogger = ClientLoggers.default(tag: "AutoRestUrlMutliCollectionFormatTest"),
        telemetryOptions: TelemetryOptions = TelemetryOptions(),
        transportOptions: TransportOptions? = nil,
        dispatchQueue: DispatchQueue? = nil
    ) {
        self.apiVersion = apiVersion.requestString
        self.logger = logger
        self.telemetryOptions = telemetryOptions
        self.transportOptions = transportOptions ?? TransportOptions()
        self.dispatchQueue = dispatchQueue
    }
}


// swift-tools-version:5.1
//  The swift-tools-version declares the minimum version of Swift required to build this package.
//
// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import PackageDescription

let package = Package(
    name: "AutoRestValidationTest",
    platforms: [
        .macOS(.v10_15), .iOS(.v12), .tvOS(.v12)
    ],
    products: [
        .library(name: "AutoRestValidationTest", type: .static, targets: ["AutoRestValidationTest"])
    ],
    dependencies: [
        .package(
            url: "https://github.com/Azure/SwiftPM-AzureCore.git",
            .branch("dev/AzureCore")
        )
    ],
    targets: [
        // Build targets
        .target(
            name: "AutoRestValidationTest",
            dependencies: ["AzureCore"],
            path: "Source"
        )
    ],
    swiftLanguageVersions: [.v5]
)


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// swiftlint:disable cyclomatic_complexity
// swiftlint:disable function_body_length
// swiftlint:disable type_body_length

public final class AutoRestValidationTest {
    public let client: AutoRestValidationTestClient

    init(client: AutoRestValidationTestClient) {
        self.client = client
    }

    /// Validates input parameters on the method. See swagger for details.
    /// - Parameters:
    ///    - resourceGroupName : Required string between 3 and 10 chars with pattern [a-zA-Z0-9]+.
    ///    - id : Required int multiple of 10 from 100 to 1000.
    ///    - options: A list of options for the operation
    ///    - completionHandler: A completion handler that receives a status code on
    ///     success.
    public func validationOfMethodParameters(
        resourceGroupName: String,
        id: Int32,
        withOptions options: ValidationOfMethodParametersOptions? = nil,
        completionHandler: @escaping HTTPResultHandler<Product>
    ) {
        let dispatchQueue = options?.dispatchQueue ?? client.commonOptions.dispatchQueue ?? DispatchQueue.main

        // Create request parameters
        let params = RequestParameters(
            (.path, "resourceGroupName", resourceGroupName, .encode), (.path, "id", id, .encode),
            (.uri, "$host", client.endpoint.absoluteString, .skipEncoding),
            (.path, "subscriptionId", client.subscriptionId, .encode),
            (.query, "apiVersion", client.options.apiVersion, .encode), (.header, "Accept", "application/json", .encode)
        )

        // Construct request
        let urlTemplate = "/fakepath/{subscriptionId}/{resourceGroupName}/{id}"
        guard let requestUrl = client.url(host: "{$host}", template: urlTemplate, params: params),
            let request = try? HTTPRequest(method: .get, url: requestUrl, headers: params.headers)
        else {
            client.options.logger.error("Failed to construct HTTP request.")
            return
        }

        // Apply client-side validation
        var validationErrors = [String]()
        // Validate id
        if id % (10 as Int32) != 0 {
            validationErrors.append("id: multipleOf 10")
        }
        if id > 1000 {
            validationErrors.append("id: <= 1000")
        }
        if id < 100 {
            validationErrors.append("id: >= 100")
        }
        // Validate resourceGroupName
        if resourceGroupName.count > 10 {
            validationErrors.append("resourceGroupName: maxLength 10")
        }
        if resourceGroupName.count < 3 {
            validationErrors.append("resourceGroupName: minLength 3")
        }
        if resourceGroupName.range(of: #"[a-zA-Z0-9']+"#, options: .regularExpression) == nil {
            validationErrors.append(#"resourceGroupName: pattern [a-zA-Z0-9']+"#)
        }
        if !validationErrors.isEmpty {
            dispatchQueue.async {
                let error = AzureError.client("Validation Errors: \(validationErrors.joined(separator: ", "))")
                completionHandler(.failure(error), nil)
            }
            return
        }

        // Send request
        let context = PipelineContext.of(keyValues: [
            ContextKey.allowedStatusCodes.rawValue: [200] as AnyObject
        ])
        context.add(cancellationToken: options?.cancellationToken, applying: client.options)
        context.merge(with: options?.context)
        client.request(request, context: context) { result, httpResponse in
            guard let data = httpResponse?.data else {
                let noDataError = AzureError.client("Response data expected but not found.")
                dispatchQueue.async {
                    completionHandler(.failure(noDataError), httpResponse)
                }
                return
            }
            switch result {
            case .success:
                guard let statusCode = httpResponse?.statusCode else {
                    let noStatusCodeError = AzureError.client("Expected a status code in response but didn't find one.")
                    dispatchQueue.async {
                        completionHandler(.failure(noStatusCodeError), httpResponse)
                    }
                    return
                }
                if [
                    200
                ].contains(statusCode) {
                    do {
                        let decoder = JSONDecoder()
                        let decoded = try decoder.decode(Product.self, from: data)
                        dispatchQueue.async {
                            completionHandler(.success(decoded), httpResponse)
                        }
                    } catch {
                        dispatchQueue.async {
                            completionHandler(.failure(AzureError.client("Decoding error.", error)), httpResponse)
                        }
                    }
                }
            case .failure:
                do {
                    let decoder = JSONDecoder()
                    let decoded = try decoder.decode(ErrorType.self, from: data)
                    dispatchQueue.async {
                        completionHandler(.failure(AzureError.service("Unexpected error", decoded)), httpResponse)
                    }
                } catch {
                    dispatchQueue.async {
                        completionHandler(.failure(AzureError.client("Decoding error.", error)), httpResponse)
                    }
                }
            }
        }
    }

    /// Validates body parameters on the method. See swagger for details.
    /// - Parameters:
    ///    - ofBody :
    ///    - resourceGroupName : Required string between 3 and 10 chars with pattern [a-zA-Z0-9]+.
    ///    - id : Required int multiple of 10 from 100 to 1000.
    ///    - options: A list of options for the operation
    ///    - completionHandler: A completion handler that receives a status code on
    ///     success.
    public func validation(
        ofBody: Product?,
        resourceGroupName: String,
        id: Int32,
        withOptions options: ValidationOfBodyOptions? = nil,
        completionHandler: @escaping HTTPResultHandler<Product>
    ) {
        let dispatchQueue = options?.dispatchQueue ?? client.commonOptions.dispatchQueue ?? DispatchQueue.main

        // Create request parameters
        let params = RequestParameters(
            (.path, "resourceGroupName", resourceGroupName, .encode), (.path, "id", id, .encode),
            (.uri, "$host", client.endpoint.absoluteString, .skipEncoding),
            (.path, "subscriptionId", client.subscriptionId, .encode),
            (.query, "apiVersion", client.options.apiVersion, .encode),
            (.header, "Content-Type", "application/json", .encode), (.header, "Accept", "application/json", .encode)
        )

        // Construct request
        var requestBody: Data?
        if ofBody != nil {
            guard let encodedRequestBody = try? JSONEncoder().encode(ofBody) else {
                client.options.logger.error("Failed to encode request body as json.")
                return
            }
            requestBody = encodedRequestBody
        }
        let urlTemplate = "/fakepath/{subscriptionId}/{resourceGroupName}/{id}"
        guard let requestUrl = client.url(host: "{$host}", template: urlTemplate, params: params),
            let request = try? HTTPRequest(method: .put, url: requestUrl, headers: params.headers, data: requestBody)
        else {
            client.options.logger.error("Failed to construct HTTP request.")
            return
        }

        // Apply client-side validation
        var validationErrors = [String]()
        // Validate id
        if id % (10 as Int32) != 0 {
            validationErrors.append("id: multipleOf 10")
        }
        if id > 1000 {
            validationErrors.append("id: <= 1000")
        }
        if id < 100 {
            validationErrors.append("id: >= 100")
        }
        // Validate ofBody?.capacity
        if let value = ofBody?.capacity, value >= 100 {
            validationErrors.append("ofBody?.capacity: < 100")
        }
        if let value = ofBody?.capacity, value <= 0 {
            validationErrors.append("ofBody?.capacity: > 0")
        }
        // Validate ofBody?.displayNames
        if let value = ofBody?.displayNames, value.count > 6 {
            validationErrors.append("ofBody?.displayNames: maxItems 6")
        }
        // Validate ofBody?.image
        if let value = ofBody?.image, value.range(of: #"http://\w+"#, options: .regularExpression) == nil {
            validationErrors.append(#"ofBody?.image: pattern http://\w+"#)
        }
        // Validate resourceGroupName
        if resourceGroupName.count > 10 {
            validationErrors.append("resourceGroupName: maxLength 10")
        }
        if resourceGroupName.count < 3 {
            validationErrors.append("resourceGroupName: minLength 3")
        }
        if resourceGroupName.range(of: #"[a-zA-Z0-9]+"#, options: .regularExpression) == nil {
            validationErrors.append(#"resourceGroupName: pattern [a-zA-Z0-9]+"#)
        }
        if !validationErrors.isEmpty {
            dispatchQueue.async {
                let error = AzureError.client("Validation Errors: \(validationErrors.joined(separator: ", "))")
                completionHandler(.failure(error), nil)
            }
            return
        }

        // Send request
        let context = PipelineContext.of(keyValues: [
            ContextKey.allowedStatusCodes.rawValue: [200] as AnyObject
        ])
        context.add(cancellationToken: options?.cancellationToken, applying: client.options)
        context.merge(with: options?.context)
        client.request(request, context: context) { result, httpResponse in
            guard let data = httpResponse?.data else {
                let noDataError = AzureError.client("Response data expected but not found.")
                dispatchQueue.async {
                    completionHandler(.failure(noDataError), httpResponse)
                }
                return
            }
            switch result {
            case .success:
                guard let statusCode = httpResponse?.statusCode else {
                    let noStatusCodeError = AzureError.client("Expected a status code in response but didn't find one.")
                    dispatchQueue.async {
                        completionHandler(.failure(noStatusCodeError), httpResponse)
                    }
                    return
                }
                if [
                    200
                ].contains(statusCode) {
                    do {
                        let decoder = JSONDecoder()
                        let decoded = try decoder.decode(Product.self, from: data)
                        dispatchQueue.async {
                            completionHandler(.success(decoded), httpResponse)
                        }
                    } catch {
                        dispatchQueue.async {
                            completionHandler(.failure(AzureError.client("Decoding error.", error)), httpResponse)
                        }
                    }
                }
            case .failure:
                do {
                    let decoder = JSONDecoder()
                    let decoded = try decoder.decode(ErrorType.self, from: data)
                    dispatchQueue.async {
                        completionHandler(.failure(AzureError.service("Unexpected error", decoded)), httpResponse)
                    }
                } catch {
                    dispatchQueue.async {
                        completionHandler(.failure(AzureError.client("Decoding error.", error)), httpResponse)
                    }
                }
            }
        }
    }

    /// - Parameters:

    ///    - options: A list of options for the operation
    ///    - completionHandler: A completion handler that receives a status code on
    ///     success.
    public func getWithConstantInPath(
        withOptions options: GetWithConstantInPathOptions? = nil,
        completionHandler: @escaping HTTPResultHandler<Void>
    ) {
        let dispatchQueue = options?.dispatchQueue ?? client.commonOptions.dispatchQueue ?? DispatchQueue.main

        // Create request parameters
        let params = RequestParameters(
            (.uri, "$host", client.endpoint.absoluteString, .skipEncoding),
            (.path, "constantParam", "constant", .encode)
        )

        // Construct request
        let urlTemplate = "/validation/constantsInPath/{constantParam}/value"
        guard let requestUrl = client.url(host: "{$host}", template: urlTemplate, params: params),
            let request = try? HTTPRequest(method: .get, url: requestUrl, headers: params.headers)
        else {
            client.options.logger.error("Failed to construct HTTP request.")
            return
        }

        // Send request
        let context = PipelineContext.of(keyValues: [
            ContextKey.allowedStatusCodes.rawValue: [200] as AnyObject
        ])
        context.add(cancellationToken: options?.cancellationToken, applying: client.options)
        context.merge(with: options?.context)
        client.request(request, context: context) { result, httpResponse in
            switch result {
            case .success:
                guard let statusCode = httpResponse?.statusCode else {
                    let noStatusCodeError = AzureError.client("Expected a status code in response but didn't find one.")
                    dispatchQueue.async {
                        completionHandler(.failure(noStatusCodeError), httpResponse)
                    }
                    return
                }
                if [
                    200
                ].contains(statusCode) {
                    dispatchQueue.async {
                        completionHandler(
                            .success(()),
                            httpResponse
                        )
                    }
                }
            case let .failure(error):
                dispatchQueue.async {
                    completionHandler(.failure(error), httpResponse)
                }
            }
        }
    }

    /// - Parameters:
    ///    - withConstantInBody :
    ///    - options: A list of options for the operation
    ///    - completionHandler: A completion handler that receives a status code on
    ///     success.
    public func post(
        withConstantInBody: Product?,
        withOptions options: PostWithConstantInBodyOptions? = nil,
        completionHandler: @escaping HTTPResultHandler<Product>
    ) {
        let dispatchQueue = options?.dispatchQueue ?? client.commonOptions.dispatchQueue ?? DispatchQueue.main

        // Create request parameters
        let params = RequestParameters(
            (.uri, "$host", client.endpoint.absoluteString, .skipEncoding),
            (.path, "constantParam", "constant", .encode),
            (.header, "Content-Type", "application/json", .encode), (.header, "Accept", "application/json", .encode)
        )

        // Construct request
        var requestBody: Data?
        if withConstantInBody != nil {
            guard let encodedRequestBody = try? JSONEncoder().encode(withConstantInBody) else {
                client.options.logger.error("Failed to encode request body as json.")
                return
            }
            requestBody = encodedRequestBody
        }
        let urlTemplate = "/validation/constantsInPath/{constantParam}/value"
        guard let requestUrl = client.url(host: "{$host}", template: urlTemplate, params: params),
            let request = try? HTTPRequest(method: .post, url: requestUrl, headers: params.headers, data: requestBody)
        else {
            client.options.logger.error("Failed to construct HTTP request.")
            return
        }

        // Apply client-side validation
        var validationErrors = [String]()
        // Validate withConstantInBody?.capacity
        if let value = withConstantInBody?.capacity, value >= 100 {
            validationErrors.append("withConstantInBody?.capacity: < 100")
        }
        if let value = withConstantInBody?.capacity, value <= 0 {
            validationErrors.append("withConstantInBody?.capacity: > 0")
        }
        // Validate withConstantInBody?.displayNames
        if let value = withConstantInBody?.displayNames, value.count > 6 {
            validationErrors.append("withConstantInBody?.displayNames: maxItems 6")
        }
        // Validate withConstantInBody?.image
        if let value = withConstantInBody?.image, value.range(of: #"http://\w+"#, options: .regularExpression) == nil {
            validationErrors.append(#"withConstantInBody?.image: pattern http://\w+"#)
        }
        if !validationErrors.isEmpty {
            dispatchQueue.async {
                let error = AzureError.client("Validation Errors: \(validationErrors.joined(separator: ", "))")
                completionHandler(.failure(error), nil)
            }
            return
        }

        // Send request
        let context = PipelineContext.of(keyValues: [
            ContextKey.allowedStatusCodes.rawValue: [200] as AnyObject
        ])
        context.add(cancellationToken: options?.cancellationToken, applying: client.options)
        context.merge(with: options?.context)
        client.request(request, context: context) { result, httpResponse in
            guard let data = httpResponse?.data else {
                let noDataError = AzureError.client("Response data expected but not found.")
                dispatchQueue.async {
                    completionHandler(.failure(noDataError), httpResponse)
                }
                return
            }
            switch result {
            case .success:
                guard let statusCode = httpResponse?.statusCode else {
                    let noStatusCodeError = AzureError.client("Expected a status code in response but didn't find one.")
                    dispatchQueue.async {
                        completionHandler(.failure(noStatusCodeError), httpResponse)
                    }
                    return
                }
                if [
                    200
                ].contains(statusCode) {
                    do {
                        let decoder = JSONDecoder()
                        let decoded = try decoder.decode(Product.self, from: data)
                        dispatchQueue.async {
                            completionHandler(.success(decoded), httpResponse)
                        }
                    } catch {
                        dispatchQueue.async {
                            completionHandler(.failure(AzureError.client("Decoding error.", error)), httpResponse)
                        }
                    }
                }
            case let .failure(error):
                dispatchQueue.async {
                    completionHandler(.failure(error), httpResponse)
                }
            }
        }
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// swiftlint:disable cyclomatic_complexity
// swiftlint:disable function_body_length
// swiftlint:disable type_body_length

public final class AutoRestValidationTestClient: PipelineClient {
    /// Options provided to configure this `AutoRestValidationTestClient`.
    public let options: AutoRestValidationTestClientOptions

    // MARK: Initializers

    /// Create a AutoRestValidationTestClient client.
    /// - Parameters:
    ///   - endpoint: Base URL for the AutoRestValidationTestClient.
    ///   - authPolicy: An `Authenticating` policy to use for authenticating client requests.
    ///   - options: Options used to configure the client.
    public init(
        subscriptionId: String,
        url: URL? = nil,
        authPolicy: Authenticating,
        withOptions options: AutoRestValidationTestClientOptions
    ) throws {
        let defaultHost = URL(string: "http://localhost:3000")
        guard let endpoint = url ?? defaultHost else {
            fatalError("Unable to determine base URL. ")
        }
        self.subscriptionId = subscriptionId
        self.options = options
        super.init(
            endpoint: endpoint,
            transport: options.transportOptions.transport ?? URLSessionTransport(),
            policies: [
                UserAgentPolicy(for: AutoRestValidationTestClient.self, telemetryOptions: options.telemetryOptions),
                RequestIdPolicy(),
                AddDatePolicy(),
                authPolicy,
                ContentDecodePolicy(),
                LoggingPolicy(),
                NormalizeETagPolicy()
            ],
            logger: options.logger,
            options: options
        )
    }

    // /// Subscription ID.
    public var subscriptionId: String

    public lazy var autoRestValidationTest = AutoRestValidationTest(client: self)

    // MARK: Client Methods
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length
// swiftlint:disable cyclomatic_complexity

/// The product documentation.
public struct ChildProduct: Codable {
    // MARK: Properties

    /// Count
    public let count: Int32?

    // MARK: Constants

    /// Constant string
    public let constProperty = "constant"

    // MARK: Initializers

    /// Initialize a `ChildProduct` structure.
    /// - Parameters:
    ///   - count: Count
    public init(
        count: Int32? = nil
    ) {
        self.count = count
    }

    // MARK: Codable

    enum CodingKeys: String, CodingKey {
        case count = "count"
        case constProperty = "constProperty"
    }

    /// Initialize a `ChildProduct` structure from decoder
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.count = try? container.decode(Int32.self, forKey: .count)
    }

    /// Encode a `ChildProduct` structure
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        if count != nil { try? container.encode(count, forKey: .count) }
        try container.encode(constProperty, forKey: .constProperty)
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length
// swiftlint:disable cyclomatic_complexity

/// The product documentation.
public struct ConstantProduct: Codable {
    // MARK: Properties

    // MARK: Constants

    /// Constant string
    public let constProperty = "constant"
    /// Constant string2
    public let constProperty2 = "constant2"

    // MARK: Initializers

    /// Initialize a `ConstantProduct` structure.
    /// - Parameters:
    public init(
    ) {}

    // MARK: Codable

    enum CodingKeys: String, CodingKey {
        case constProperty = "constProperty"
        case constProperty2 = "constProperty2"
    }

    /// Initialize a `ConstantProduct` structure from decoder
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
    }

    /// Encode a `ConstantProduct` structure
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(constProperty, forKey: .constProperty)
        try container.encode(constProperty2, forKey: .constProperty2)
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length
// swiftlint:disable cyclomatic_complexity

public struct ErrorType: Codable, Swift.Error {
    // MARK: Properties

    public let code: Int32?

    public let message: String?

    public let fields: String?

    // MARK: Initializers

    /// Initialize a `ErrorType` structure.
    /// - Parameters:
    ///   - code:
    ///   - message:
    ///   - fields:
    public init(
        code: Int32? = nil, message: String? = nil, fields: String? = nil
    ) {
        self.code = code
        self.message = message
        self.fields = fields
    }

    // MARK: Codable

    enum CodingKeys: String, CodingKey {
        case code = "code"
        case message = "message"
        case fields = "fields"
    }

    /// Initialize a `ErrorType` structure from decoder
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.code = try? container.decode(Int32.self, forKey: .code)
        self.message = try? container.decode(String.self, forKey: .message)
        self.fields = try? container.decode(String.self, forKey: .fields)
    }

    /// Encode a `ErrorType` structure
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        if code != nil { try? container.encode(code, forKey: .code) }
        if message != nil { try? container.encode(message, forKey: .message) }
        if fields != nil { try? container.encode(fields, forKey: .fields) }
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length
// swiftlint:disable cyclomatic_complexity

/// The product documentation.
public struct Product: Codable {
    // MARK: Properties

    /// Non required array of unique items from 0 to 6 elements.
    public let displayNames: [String]?
    /// Non required int betwen 0 and 100 exclusive.
    public let capacity: Int32?
    /// Image URL representing the product.
    public let image: String?
    /// The product documentation.
    public let child: ChildProduct
    /// The product documentation.
    public let constChild: ConstantProduct

    // MARK: Constants

    /// Constant int
    public let constInt = 0
    /// Constant string
    public let constString = "constant"
    /// Constant string as Enum
    public let constStringAsEnum = "constant_string_as_enum"

    // MARK: Initializers

    /// Initialize a `Product` structure.
    /// - Parameters:
    ///   - displayNames: Non required array of unique items from 0 to 6 elements.
    ///   - capacity: Non required int betwen 0 and 100 exclusive.
    ///   - image: Image URL representing the product.
    ///   - child: The product documentation.
    ///   - constChild: The product documentation.
    public init(
        displayNames: [String]? = nil, capacity: Int32? = nil, image: String? = nil, child: ChildProduct,
        constChild: ConstantProduct
    ) {
        self.displayNames = displayNames
        self.capacity = capacity
        self.image = image
        self.child = child
        self.constChild = constChild
    }

    // MARK: Codable

    enum CodingKeys: String, CodingKey {
        case displayNames = "display_names"
        case capacity = "capacity"
        case image = "image"
        case child = "child"
        case constChild = "constChild"
        case constInt = "constInt"
        case constString = "constString"
        case constStringAsEnum = "constStringAsEnum"
    }

    /// Initialize a `Product` structure from decoder
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.displayNames = try? container.decode([String].self, forKey: .displayNames)
        self.capacity = try? container.decode(Int32.self, forKey: .capacity)
        self.image = try? container.decode(String.self, forKey: .image)
        self.child = try container.decode(ChildProduct.self, forKey: .child)
        self.constChild = try container.decode(ConstantProduct.self, forKey: .constChild)
    }

    /// Encode a `Product` structure
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        if displayNames != nil { try? container.encode(displayNames, forKey: .displayNames) }
        if capacity != nil { try? container.encode(capacity, forKey: .capacity) }
        if image != nil { try? container.encode(image, forKey: .image) }
        try container.encode(child, forKey: .child)
        try container.encode(constChild, forKey: .constChild)
        try container.encode(constInt, forKey: .constInt)
        try container.encode(constString, forKey: .constString)
        try container.encode(constStringAsEnum, forKey: .constStringAsEnum)
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length

/// User-configurable client options.
public struct AutoRestValidationTestClientOptions: ClientOptions {
    /// The API version of the client to invoke.
    public let apiVersion: String
    /// The `ClientLogger` to be used by this client.
    public let logger: ClientLogger
    /// Options for configuring telemetry sent by this client.
    public let telemetryOptions: TelemetryOptions
    /// Global transport options
    public let transportOptions: TransportOptions
    /// The default dispatch queue on which to call all completion handler. Defaults to `DispatchQueue.main`.
    public let dispatchQueue: DispatchQueue?

    /// API version of the  to invoke. Defaults to the latest.
    public enum ApiVersion: RequestStringConvertible {
        /// Custom value for unrecognized enum values
        case custom(String)
        /// API version "1.0.0"
        case v100

        /// The most recent API version of the
        public static var latest: ApiVersion {
            return .v100
        }

        public var requestString: String {
            switch self {
            case let .custom(val):
                return val
            case .v100:
                return "1.0.0"
            }
        }

        public init(_ val: String) {
            switch val.lowercased() {
            case "1.0.0":
                self = .v100
            default:
                self = .custom(val)
            }
        }
    }

    /// Initialize a `AutoRestValidationTestClientOptions` structure.
    /// - Parameters:
    ///   - apiVersion: The API version of the client to invoke.
    ///   - logger: The `ClientLogger` to be used by this client.
    ///   - telemetryOptions: Options for configuring telemetry sent by this client.
    ///   - cancellationToken: A token used to make a best-effort attempt at canceling a request.
    ///   - dispatchQueue: The default dispatch queue on which to call all completion handler. Defaults to `DispatchQueue.main`.
    public init(
        apiVersion: AutoRestValidationTestClientOptions.ApiVersion = .latest,
        logger: ClientLogger = ClientLoggers.default(tag: "AutoRestValidationTest"),
        telemetryOptions: TelemetryOptions = TelemetryOptions(),
        transportOptions: TransportOptions? = nil,
        dispatchQueue: DispatchQueue? = nil
    ) {
        self.apiVersion = apiVersion.requestString
        self.logger = logger
        self.telemetryOptions = telemetryOptions
        self.transportOptions = transportOptions ?? TransportOptions()
        self.dispatchQueue = dispatchQueue
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation

// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length

/// User-configurable options for the `GetWithConstantInPath` operation.
public struct GetWithConstantInPathOptions: RequestOptions {
    /// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    /// Highly recommended for correlating client-side activites with requests received by the server.
    public let clientRequestId: String?

    /// A token used to make a best-effort attempt at canceling a request.
    public let cancellationToken: CancellationToken?

    /// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    public var dispatchQueue: DispatchQueue?

    /// A `PipelineContext` object to associate with the request.
    public var context: PipelineContext?

    /// Initialize a `GetWithConstantInPathOptions` structure.
    /// - Parameters:
    ///   - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    ///   - cancellationToken: A token used to make a best-effort attempt at canceling a request.
    ///   - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    ///   - context: A `PipelineContext` object to associate with the request.
    public init(
        clientRequestId: String? = nil,
        cancellationToken: CancellationToken? = nil,
        dispatchQueue: DispatchQueue? = nil,
        context: PipelineContext? = nil
    ) {
        self.clientRequestId = clientRequestId
        self.cancellationToken = cancellationToken
        self.dispatchQueue = dispatchQueue
        self.context = context
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation

// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length

/// User-configurable options for the `PostWithConstantInBody` operation.
public struct PostWithConstantInBodyOptions: RequestOptions {
    /// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    /// Highly recommended for correlating client-side activites with requests received by the server.
    public let clientRequestId: String?

    /// A token used to make a best-effort attempt at canceling a request.
    public let cancellationToken: CancellationToken?

    /// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    public var dispatchQueue: DispatchQueue?

    /// A `PipelineContext` object to associate with the request.
    public var context: PipelineContext?

    /// Initialize a `PostWithConstantInBodyOptions` structure.
    /// - Parameters:
    ///   - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    ///   - cancellationToken: A token used to make a best-effort attempt at canceling a request.
    ///   - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    ///   - context: A `PipelineContext` object to associate with the request.
    public init(
        clientRequestId: String? = nil,
        cancellationToken: CancellationToken? = nil,
        dispatchQueue: DispatchQueue? = nil,
        context: PipelineContext? = nil
    ) {
        self.clientRequestId = clientRequestId
        self.cancellationToken = cancellationToken
        self.dispatchQueue = dispatchQueue
        self.context = context
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation

// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length

/// User-configurable options for the `ValidationOfBody` operation.
public struct ValidationOfBodyOptions: RequestOptions {
    /// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    /// Highly recommended for correlating client-side activites with requests received by the server.
    public let clientRequestId: String?

    /// A token used to make a best-effort attempt at canceling a request.
    public let cancellationToken: CancellationToken?

    /// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    public var dispatchQueue: DispatchQueue?

    /// A `PipelineContext` object to associate with the request.
    public var context: PipelineContext?

    /// Initialize a `ValidationOfBodyOptions` structure.
    /// - Parameters:
    ///   - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    ///   - cancellationToken: A token used to make a best-effort attempt at canceling a request.
    ///   - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    ///   - context: A `PipelineContext` object to associate with the request.
    public init(
        clientRequestId: String? = nil,
        cancellationToken: CancellationToken? = nil,
        dispatchQueue: DispatchQueue? = nil,
        context: PipelineContext? = nil
    ) {
        self.clientRequestId = clientRequestId
        self.cancellationToken = cancellationToken
        self.dispatchQueue = dispatchQueue
        self.context = context
    }
}


// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import AzureCore
import Foundation

// swiftlint:disable superfluous_disable_command
// swiftlint:disable identifier_name
// swiftlint:disable line_length

/// User-configurable options for the `ValidationOfMethodParameters` operation.
public struct ValidationOfMethodParametersOptions: RequestOptions {
    /// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    /// Highly recommended for correlating client-side activites with requests received by the server.
    public let clientRequestId: String?

    /// A token used to make a best-effort attempt at canceling a request.
    public let cancellationToken: CancellationToken?

    /// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    public var dispatchQueue: DispatchQueue?

    /// A `PipelineContext` object to associate with the request.
    public var context: PipelineContext?

    /// Initialize a `ValidationOfMethodParametersOptions` structure.
    /// - Parameters:
    ///   - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs.
    ///   - cancellationToken: A token used to make a best-effort attempt at canceling a request.
    ///   - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`.
    ///   - context: A `PipelineContext` object to associate with the request.
    public init(
        clientRequestId: String? = nil,
        cancellationToken: CancellationToken? = nil,
        dispatchQueue: DispatchQueue? = nil,
        context: PipelineContext? = nil
    ) {
        self.clientRequestId = clientRequestId
        self.cancellationToken = cancellationToken
        self.dispatchQueue = dispatchQueue
        self.context = context
    }
}


import Foundation

// TODO: Remove this when these objects are in AzureCore

enum MergePatchOpType: String, Codable {
    case add
    case remove
    case replace
    case move
    case copy
    case test
}

// TODO: NO support for nil-setting sentinel

struct MergePatchOperation: Encodable {
    let operation: MergePatchOpType
    let from: String?
    let path: String
    let value: String?

    // MARK: Encodable

    enum CodingKeys: String, CodingKey {
        case operation, from, path, value
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(operation, forKey: .operation)
        try container.encode(from, forKey: .from)
        try container.encode(path, forKey: .path)
        try container.encode(value, forKey: .value)
    }
}

/// Helper class for creating PatchObjects
final class MergePatchObject: Encodable {
    fileprivate var operations = [MergePatchOperation]()

    /// Inserts a new value at an array index or adds a new property.
    func add(atPath path: String, withValue value: String) {
        operations.append(MergePatchOperation(operation: .add, from: nil, path: path, value: value))
    }

    /// Remove the property or entry at an array index. Property must exist.
    func remove(atPath path: String) {
        operations.append(MergePatchOperation(operation: .remove, from: nil, path: path, value: nil))
    }

    /// Replaces the value at the target location with a new value. Existing value must exist.
    func replace(atPath path: String, withValue value: String) {
        operations.append(MergePatchOperation(operation: .replace, from: nil, path: path, value: value))
    }

    /// Remove the value at a specified location and adds it to the target location.
    func move(fromPath src: String, toPath dest: String) {
        operations.append(MergePatchOperation(operation: .move, from: src, path: dest, value: nil))
    }

    /// Copies the value at a specified location and adds it to the target location.
    func copy(fromPath src: String, toPath dest: String) {
        operations.append(MergePatchOperation(operation: .copy, from: src, path: dest, value: nil))
    }

    /// Tests that a value at the target location is equal to a specified value.
    func test(atPath path: String, equalsValue value: String) {
        operations.append(MergePatchOperation(operation: .test, from: nil, path: path, value: value))
    }
}


// swift-tools-version:5.1
//  The swift-tools-version declares the minimum version of Swift required to build this package.
//
// --------------------------------------------------------------------------
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// --------------------------------------------------------------------------

import PackageDescription

let package = Package(
    name: "XmsErrorResponseExtensions",
    platforms: [
        .macOS(.v10_15), .iOS(.v12), .tvOS(.v12)
    ],
    products: [
        .library(name: "XmsErrorResponseExtensions", type: .static, targets: ["XmsErrorResponseExtensions"])
    ],
    dependencies: [
        .package(
            url: "https://github.com/Azure/SwiftPM-AzureCore.git",
            .branch("dev/AzureCore")
        )
    ],
    targets: [
        // Build targets
        .target(
            name: "XmsErrorResponseExtensions",
            dependencies: ["AzureCore"],
            path: "Source"
        )
    ],
    swiftLanguageVersions: [.v5]
)


// --------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the ""Software""), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
// --------------------------------------------------------------------------

import Foundation

// TODO: Custom Code Here