/* 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 EdgeRegistryThingModelExtensions
    {
        public abstract partial class Service : IAsyncDisposable
        {
            private ApplicationContext applicationContext;
            private IMqttPubSubClient mqttClient;
            private readonly GetThingModelVersionActionExecutor getThingModelVersionActionExecutor;
            private readonly CreateThingModelVersionActionExecutor createThingModelVersionActionExecutor;
            private readonly ListThingModelVersionsActionExecutor listThingModelVersionsActionExecutor;
            private readonly DeleteThingModelVersionActionExecutor deleteThingModelVersionActionExecutor;

            /// <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.getThingModelVersionActionExecutor = new GetThingModelVersionActionExecutor(applicationContext, mqttClient) { OnCommandReceived = GetThingModelVersionInt };
                this.createThingModelVersionActionExecutor = new CreateThingModelVersionActionExecutor(applicationContext, mqttClient) { OnCommandReceived = CreateThingModelVersionInt };
                this.listThingModelVersionsActionExecutor = new ListThingModelVersionsActionExecutor(applicationContext, mqttClient) { OnCommandReceived = ListThingModelVersionsInt };
                this.deleteThingModelVersionActionExecutor = new DeleteThingModelVersionActionExecutor(applicationContext, mqttClient) { OnCommandReceived = DeleteThingModelVersionInt };

                if (topicTokenMap != null)
                {
                    foreach (string topicTokenKey in topicTokenMap.Keys)
                    {
                        this.getThingModelVersionActionExecutor.TopicTokenMap.TryAdd("ex:" + topicTokenKey, topicTokenMap[topicTokenKey]);
                        this.createThingModelVersionActionExecutor.TopicTokenMap.TryAdd("ex:" + topicTokenKey, topicTokenMap[topicTokenKey]);
                        this.listThingModelVersionsActionExecutor.TopicTokenMap.TryAdd("ex:" + topicTokenKey, topicTokenMap[topicTokenKey]);
                        this.deleteThingModelVersionActionExecutor.TopicTokenMap.TryAdd("ex:" + topicTokenKey, topicTokenMap[topicTokenKey]);
                    }
                }

                this.getThingModelVersionActionExecutor.TopicTokenMap.TryAdd("executorId", clientId);
                this.createThingModelVersionActionExecutor.TopicTokenMap.TryAdd("executorId", clientId);
                this.listThingModelVersionsActionExecutor.TopicTokenMap.TryAdd("executorId", clientId);
                this.deleteThingModelVersionActionExecutor.TopicTokenMap.TryAdd("executorId", clientId);
            }

            public GetThingModelVersionActionExecutor GetThingModelVersionActionExecutor { get => this.getThingModelVersionActionExecutor; }

            public CreateThingModelVersionActionExecutor CreateThingModelVersionActionExecutor { get => this.createThingModelVersionActionExecutor; }

            public ListThingModelVersionsActionExecutor ListThingModelVersionsActionExecutor { get => this.listThingModelVersionsActionExecutor; }

            public DeleteThingModelVersionActionExecutor DeleteThingModelVersionActionExecutor { get => this.deleteThingModelVersionActionExecutor; }

            public abstract Task<ExtendedResponse<GetThingModelVersionOutputArguments>> GetThingModelVersionAsync(GetThingModelVersionInputArguments request, CommandRequestMetadata requestMetadata, CancellationToken cancellationToken);

            public abstract Task<ExtendedResponse<CreateThingModelVersionOutputArguments>> CreateThingModelVersionAsync(CreateThingModelVersionInputArguments request, CommandRequestMetadata requestMetadata, CancellationToken cancellationToken);

            public abstract Task<ExtendedResponse<ListThingModelVersionsOutputArguments>> ListThingModelVersionsAsync(ListThingModelVersionsInputArguments request, CommandRequestMetadata requestMetadata, CancellationToken cancellationToken);

            public abstract Task<ExtendedResponse<EmptyJson>> DeleteThingModelVersionAsync(DeleteThingModelVersionInputArguments 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.getThingModelVersionActionExecutor.StartAsync(preferredDispatchConcurrency, cancellationToken),
                    this.createThingModelVersionActionExecutor.StartAsync(preferredDispatchConcurrency, cancellationToken),
                    this.listThingModelVersionsActionExecutor.StartAsync(preferredDispatchConcurrency, cancellationToken),
                    this.deleteThingModelVersionActionExecutor.StartAsync(preferredDispatchConcurrency, cancellationToken)).ConfigureAwait(false);
            }

            public async Task StopAsync(CancellationToken cancellationToken = default)
            {
                await Task.WhenAll(
                    this.getThingModelVersionActionExecutor.StopAsync(cancellationToken),
                    this.createThingModelVersionActionExecutor.StopAsync(cancellationToken),
                    this.listThingModelVersionsActionExecutor.StopAsync(cancellationToken),
                    this.deleteThingModelVersionActionExecutor.StopAsync(cancellationToken)).ConfigureAwait(false);
            }

            private async Task<ExtendedResponse<GetThingModelVersionResponseSchema>> GetThingModelVersionInt(ExtendedRequest<GetThingModelVersionInputArguments> req, CancellationToken cancellationToken)
            {
                try
                {
                    ExtendedResponse<GetThingModelVersionOutputArguments> extended = await this.GetThingModelVersionAsync(req.Request!, req.RequestMetadata!, cancellationToken);

                    return new ExtendedResponse<GetThingModelVersionResponseSchema>
                    {
                        Response = new GetThingModelVersionResponseSchema
                        {
                            Output = extended.Response,
                        },
                        ResponseMetadata = extended.ResponseMetadata,
                    };
                }
                catch (ThingModelExtensionErrorException intEx)
                {
                    ExtendedResponse<GetThingModelVersionResponseSchema> extendedResponse = ExtendedResponse<GetThingModelVersionResponseSchema>.CreateFromResponse(new GetThingModelVersionResponseSchema { Error = intEx.ThingModelExtensionError });
                    return extendedResponse;
                }
            }

            private async Task<ExtendedResponse<CreateThingModelVersionResponseSchema>> CreateThingModelVersionInt(ExtendedRequest<CreateThingModelVersionInputArguments> req, CancellationToken cancellationToken)
            {
                try
                {
                    ExtendedResponse<CreateThingModelVersionOutputArguments> extended = await this.CreateThingModelVersionAsync(req.Request!, req.RequestMetadata!, cancellationToken);

                    return new ExtendedResponse<CreateThingModelVersionResponseSchema>
                    {
                        Response = new CreateThingModelVersionResponseSchema
                        {
                            Output = extended.Response,
                        },
                        ResponseMetadata = extended.ResponseMetadata,
                    };
                }
                catch (ThingModelExtensionErrorException intEx)
                {
                    ExtendedResponse<CreateThingModelVersionResponseSchema> extendedResponse = ExtendedResponse<CreateThingModelVersionResponseSchema>.CreateFromResponse(new CreateThingModelVersionResponseSchema { Error = intEx.ThingModelExtensionError });
                    return extendedResponse;
                }
            }

            private async Task<ExtendedResponse<ListThingModelVersionsResponseSchema>> ListThingModelVersionsInt(ExtendedRequest<ListThingModelVersionsInputArguments> req, CancellationToken cancellationToken)
            {
                try
                {
                    ExtendedResponse<ListThingModelVersionsOutputArguments> extended = await this.ListThingModelVersionsAsync(req.Request!, req.RequestMetadata!, cancellationToken);

                    return new ExtendedResponse<ListThingModelVersionsResponseSchema>
                    {
                        Response = new ListThingModelVersionsResponseSchema
                        {
                            Output = extended.Response,
                        },
                        ResponseMetadata = extended.ResponseMetadata,
                    };
                }
                catch (ThingModelExtensionErrorException intEx)
                {
                    ExtendedResponse<ListThingModelVersionsResponseSchema> extendedResponse = ExtendedResponse<ListThingModelVersionsResponseSchema>.CreateFromResponse(new ListThingModelVersionsResponseSchema { Error = intEx.ThingModelExtensionError });
                    return extendedResponse;
                }
            }

            private async Task<ExtendedResponse<DeleteThingModelVersionResponseSchema>> DeleteThingModelVersionInt(ExtendedRequest<DeleteThingModelVersionInputArguments> req, CancellationToken cancellationToken)
            {
                try
                {
                    ExtendedResponse<EmptyJson> extended = await this.DeleteThingModelVersionAsync(req.Request!, req.RequestMetadata!, cancellationToken);

                    return new ExtendedResponse<DeleteThingModelVersionResponseSchema>
                    {
                        Response = new DeleteThingModelVersionResponseSchema
                        {
                        },
                        ResponseMetadata = extended.ResponseMetadata,
                    };
                }
                catch (ThingModelExtensionErrorException intEx)
                {
                    ExtendedResponse<DeleteThingModelVersionResponseSchema> extendedResponse = ExtendedResponse<DeleteThingModelVersionResponseSchema>.CreateFromResponse(new DeleteThingModelVersionResponseSchema { Error = intEx.ThingModelExtensionError });
                    return extendedResponse;
                }
            }

            public async ValueTask DisposeAsync()
            {
                await this.getThingModelVersionActionExecutor.DisposeAsync().ConfigureAwait(false);
                await this.createThingModelVersionActionExecutor.DisposeAsync().ConfigureAwait(false);
                await this.listThingModelVersionsActionExecutor.DisposeAsync().ConfigureAwait(false);
                await this.deleteThingModelVersionActionExecutor.DisposeAsync().ConfigureAwait(false);
            }

            public async ValueTask DisposeAsync(bool disposing, CancellationToken cancellationToken = default)
            {
                await this.getThingModelVersionActionExecutor.DisposeAsync(disposing, cancellationToken).ConfigureAwait(false);
                await this.createThingModelVersionActionExecutor.DisposeAsync(disposing, cancellationToken).ConfigureAwait(false);
                await this.listThingModelVersionsActionExecutor.DisposeAsync(disposing, cancellationToken).ConfigureAwait(false);
                await this.deleteThingModelVersionActionExecutor.DisposeAsync(disposing, cancellationToken).ConfigureAwait(false);
            }
        }
    }
}
