/* Code generated by Azure.Iot.Operations.ProtocolCompilerLib v1.0.0.0; DO NOT EDIT. */

#nullable enable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Iot.Operations.Protocol.Models;
using Azure.Iot.Operations.Protocol;
using Azure.Iot.Operations.Protocol.RPC;
using Azure.Iot.Operations.Protocol.Telemetry;
using Azure.Iot.Operations.Services.EdgeRegistry.Host.Generated.Common;

namespace Azure.Iot.Operations.Services.EdgeRegistry.Host.Generated
{
    [System.CodeDom.Compiler.GeneratedCode("Azure.Iot.Operations.ProtocolCompilerLib", "1.0.0.0")]
    public static partial class EdgeRegistrySchemaExtensions
    {
        public abstract partial class Service : IAsyncDisposable
        {
            private ApplicationContext applicationContext;
            private IMqttPubSubClient mqttClient;
            private readonly GetSchemaVersionActionExecutor getSchemaVersionActionExecutor;
            private readonly CreateSchemaVersionActionExecutor createSchemaVersionActionExecutor;
            private readonly ListSchemaVersionsActionExecutor listSchemaVersionsActionExecutor;
            private readonly DeleteSchemaVersionActionExecutor deleteSchemaVersionActionExecutor;

            /// <summary>
            /// Construct a new instance of this service.
            /// </summary>
            /// <param name="applicationContext">The shared context for your application.</param>
            /// <param name="mqttClient">The MQTT client to use.</param>
            /// <param name="topicTokenMap">
            /// The topic token replacement map to use for all operations by default. Generally, this will include the token values
            /// for topic tokens that should be the same for the duration of this service's lifetime. Note that
            /// additional topic tokens can be specified per event message.
            /// </param>
            public Service(ApplicationContext applicationContext, IMqttPubSubClient mqttClient, Dictionary<string, string>? topicTokenMap = null)
            {
                this.applicationContext = applicationContext;
                this.mqttClient = mqttClient;

                string? clientId = this.mqttClient.ClientId;
                if (string.IsNullOrEmpty(clientId))
                {
                    throw new InvalidOperationException("No MQTT client Id configured. Must connect to MQTT broker before invoking command.");
                }

                this.getSchemaVersionActionExecutor = new GetSchemaVersionActionExecutor(applicationContext, mqttClient) { OnCommandReceived = GetSchemaVersionInt };
                this.createSchemaVersionActionExecutor = new CreateSchemaVersionActionExecutor(applicationContext, mqttClient) { OnCommandReceived = CreateSchemaVersionInt };
                this.listSchemaVersionsActionExecutor = new ListSchemaVersionsActionExecutor(applicationContext, mqttClient) { OnCommandReceived = ListSchemaVersionsInt };
                this.deleteSchemaVersionActionExecutor = new DeleteSchemaVersionActionExecutor(applicationContext, mqttClient) { OnCommandReceived = DeleteSchemaVersionInt };

                if (topicTokenMap != null)
                {
                    foreach (string topicTokenKey in topicTokenMap.Keys)
                    {
                        this.getSchemaVersionActionExecutor.TopicTokenMap.TryAdd("ex:" + topicTokenKey, topicTokenMap[topicTokenKey]);
                        this.createSchemaVersionActionExecutor.TopicTokenMap.TryAdd("ex:" + topicTokenKey, topicTokenMap[topicTokenKey]);
                        this.listSchemaVersionsActionExecutor.TopicTokenMap.TryAdd("ex:" + topicTokenKey, topicTokenMap[topicTokenKey]);
                        this.deleteSchemaVersionActionExecutor.TopicTokenMap.TryAdd("ex:" + topicTokenKey, topicTokenMap[topicTokenKey]);
                    }
                }

                this.getSchemaVersionActionExecutor.TopicTokenMap.TryAdd("executorId", clientId);
                this.createSchemaVersionActionExecutor.TopicTokenMap.TryAdd("executorId", clientId);
                this.listSchemaVersionsActionExecutor.TopicTokenMap.TryAdd("executorId", clientId);
                this.deleteSchemaVersionActionExecutor.TopicTokenMap.TryAdd("executorId", clientId);
            }

            public GetSchemaVersionActionExecutor GetSchemaVersionActionExecutor { get => this.getSchemaVersionActionExecutor; }

            public CreateSchemaVersionActionExecutor CreateSchemaVersionActionExecutor { get => this.createSchemaVersionActionExecutor; }

            public ListSchemaVersionsActionExecutor ListSchemaVersionsActionExecutor { get => this.listSchemaVersionsActionExecutor; }

            public DeleteSchemaVersionActionExecutor DeleteSchemaVersionActionExecutor { get => this.deleteSchemaVersionActionExecutor; }

            public abstract Task<ExtendedResponse<GetSchemaVersionOutputArguments>> GetSchemaVersionAsync(GetSchemaVersionInputArguments request, CommandRequestMetadata requestMetadata, CancellationToken cancellationToken);

            public abstract Task<ExtendedResponse<CreateSchemaVersionOutputArguments>> CreateSchemaVersionAsync(CreateSchemaVersionInputArguments request, CommandRequestMetadata requestMetadata, CancellationToken cancellationToken);

            public abstract Task<ExtendedResponse<ListSchemaVersionsOutputArguments>> ListSchemaVersionsAsync(ListSchemaVersionsInputArguments request, CommandRequestMetadata requestMetadata, CancellationToken cancellationToken);

            public abstract Task<ExtendedResponse<EmptyJson>> DeleteSchemaVersionAsync(DeleteSchemaVersionInputArguments request, CommandRequestMetadata requestMetadata, CancellationToken cancellationToken);

            /// <summary>
            /// Begin accepting command invocations for all command executors.
            /// </summary>
            /// <param name="preferredDispatchConcurrency">The dispatch concurrency count for the command response cache to use.</param>
            /// <param name="cancellationToken">Cancellation token.</param>
            public async Task StartAsync(int? preferredDispatchConcurrency = null, CancellationToken cancellationToken = default)
            {
                string? clientId = this.mqttClient.ClientId;
                if (string.IsNullOrEmpty(clientId))
                {
                    throw new InvalidOperationException("No MQTT client Id configured. Must connect to MQTT broker before starting service.");
                }

                await Task.WhenAll(
                    this.getSchemaVersionActionExecutor.StartAsync(preferredDispatchConcurrency, cancellationToken),
                    this.createSchemaVersionActionExecutor.StartAsync(preferredDispatchConcurrency, cancellationToken),
                    this.listSchemaVersionsActionExecutor.StartAsync(preferredDispatchConcurrency, cancellationToken),
                    this.deleteSchemaVersionActionExecutor.StartAsync(preferredDispatchConcurrency, cancellationToken)).ConfigureAwait(false);
            }

            public async Task StopAsync(CancellationToken cancellationToken = default)
            {
                await Task.WhenAll(
                    this.getSchemaVersionActionExecutor.StopAsync(cancellationToken),
                    this.createSchemaVersionActionExecutor.StopAsync(cancellationToken),
                    this.listSchemaVersionsActionExecutor.StopAsync(cancellationToken),
                    this.deleteSchemaVersionActionExecutor.StopAsync(cancellationToken)).ConfigureAwait(false);
            }

            private async Task<ExtendedResponse<GetSchemaVersionResponseSchema>> GetSchemaVersionInt(ExtendedRequest<GetSchemaVersionInputArguments> req, CancellationToken cancellationToken)
            {
                try
                {
                    ExtendedResponse<GetSchemaVersionOutputArguments> extended = await this.GetSchemaVersionAsync(req.Request!, req.RequestMetadata!, cancellationToken);

                    return new ExtendedResponse<GetSchemaVersionResponseSchema>
                    {
                        Response = new GetSchemaVersionResponseSchema
                        {
                            Output = extended.Response,
                        },
                        ResponseMetadata = extended.ResponseMetadata,
                    };
                }
                catch (SchemaExtensionErrorException intEx)
                {
                    ExtendedResponse<GetSchemaVersionResponseSchema> extendedResponse = ExtendedResponse<GetSchemaVersionResponseSchema>.CreateFromResponse(new GetSchemaVersionResponseSchema { Error = intEx.SchemaExtensionError });
                    return extendedResponse;
                }
            }

            private async Task<ExtendedResponse<CreateSchemaVersionResponseSchema>> CreateSchemaVersionInt(ExtendedRequest<CreateSchemaVersionInputArguments> req, CancellationToken cancellationToken)
            {
                try
                {
                    ExtendedResponse<CreateSchemaVersionOutputArguments> extended = await this.CreateSchemaVersionAsync(req.Request!, req.RequestMetadata!, cancellationToken);

                    return new ExtendedResponse<CreateSchemaVersionResponseSchema>
                    {
                        Response = new CreateSchemaVersionResponseSchema
                        {
                            Output = extended.Response,
                        },
                        ResponseMetadata = extended.ResponseMetadata,
                    };
                }
                catch (SchemaExtensionErrorException intEx)
                {
                    ExtendedResponse<CreateSchemaVersionResponseSchema> extendedResponse = ExtendedResponse<CreateSchemaVersionResponseSchema>.CreateFromResponse(new CreateSchemaVersionResponseSchema { Error = intEx.SchemaExtensionError });
                    return extendedResponse;
                }
            }

            private async Task<ExtendedResponse<ListSchemaVersionsResponseSchema>> ListSchemaVersionsInt(ExtendedRequest<ListSchemaVersionsInputArguments> req, CancellationToken cancellationToken)
            {
                try
                {
                    ExtendedResponse<ListSchemaVersionsOutputArguments> extended = await this.ListSchemaVersionsAsync(req.Request!, req.RequestMetadata!, cancellationToken);

                    return new ExtendedResponse<ListSchemaVersionsResponseSchema>
                    {
                        Response = new ListSchemaVersionsResponseSchema
                        {
                            Output = extended.Response,
                        },
                        ResponseMetadata = extended.ResponseMetadata,
                    };
                }
                catch (SchemaExtensionErrorException intEx)
                {
                    ExtendedResponse<ListSchemaVersionsResponseSchema> extendedResponse = ExtendedResponse<ListSchemaVersionsResponseSchema>.CreateFromResponse(new ListSchemaVersionsResponseSchema { Error = intEx.SchemaExtensionError });
                    return extendedResponse;
                }
            }

            private async Task<ExtendedResponse<DeleteSchemaVersionResponseSchema>> DeleteSchemaVersionInt(ExtendedRequest<DeleteSchemaVersionInputArguments> req, CancellationToken cancellationToken)
            {
                try
                {
                    ExtendedResponse<EmptyJson> extended = await this.DeleteSchemaVersionAsync(req.Request!, req.RequestMetadata!, cancellationToken);

                    return new ExtendedResponse<DeleteSchemaVersionResponseSchema>
                    {
                        Response = new DeleteSchemaVersionResponseSchema
                        {
                        },
                        ResponseMetadata = extended.ResponseMetadata,
                    };
                }
                catch (SchemaExtensionErrorException intEx)
                {
                    ExtendedResponse<DeleteSchemaVersionResponseSchema> extendedResponse = ExtendedResponse<DeleteSchemaVersionResponseSchema>.CreateFromResponse(new DeleteSchemaVersionResponseSchema { Error = intEx.SchemaExtensionError });
                    return extendedResponse;
                }
            }

            public async ValueTask DisposeAsync()
            {
                await this.getSchemaVersionActionExecutor.DisposeAsync().ConfigureAwait(false);
                await this.createSchemaVersionActionExecutor.DisposeAsync().ConfigureAwait(false);
                await this.listSchemaVersionsActionExecutor.DisposeAsync().ConfigureAwait(false);
                await this.deleteSchemaVersionActionExecutor.DisposeAsync().ConfigureAwait(false);
            }

            public async ValueTask DisposeAsync(bool disposing, CancellationToken cancellationToken = default)
            {
                await this.getSchemaVersionActionExecutor.DisposeAsync(disposing, cancellationToken).ConfigureAwait(false);
                await this.createSchemaVersionActionExecutor.DisposeAsync(disposing, cancellationToken).ConfigureAwait(false);
                await this.listSchemaVersionsActionExecutor.DisposeAsync(disposing, cancellationToken).ConfigureAwait(false);
                await this.deleteSchemaVersionActionExecutor.DisposeAsync(disposing, cancellationToken).ConfigureAwait(false);
            }
        }
    }
}
