/* 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.SchemaRegistry.Generated.Common;

namespace Azure.Iot.Operations.Services.SchemaRegistry.Generated
{
    [System.CodeDom.Compiler.GeneratedCode("Azure.Iot.Operations.ProtocolCompilerLib", "1.0.0.0")]
    public static partial class SchemaRegistry
    {
        public abstract partial class Service : IAsyncDisposable
        {
            private ApplicationContext applicationContext;
            private IMqttPubSubClient mqttClient;
            private readonly PutCommandExecutor putCommandExecutor;
            private readonly GetCommandExecutor getCommandExecutor;

            /// <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.putCommandExecutor = new PutCommandExecutor(applicationContext, mqttClient) { OnCommandReceived = PutInt };
                this.getCommandExecutor = new GetCommandExecutor(applicationContext, mqttClient) { OnCommandReceived = GetInt };

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

                this.putCommandExecutor.TopicTokenMap.TryAdd("executorId", clientId);
                this.getCommandExecutor.TopicTokenMap.TryAdd("executorId", clientId);
            }

            public PutCommandExecutor PutCommandExecutor { get => this.putCommandExecutor; }

            public GetCommandExecutor GetCommandExecutor { get => this.getCommandExecutor; }

            public abstract Task<ExtendedResponse<PutResponsePayload>> PutAsync(PutRequestSchema request, CommandRequestMetadata requestMetadata, CancellationToken cancellationToken);

            public abstract Task<ExtendedResponse<GetResponsePayload>> GetAsync(GetRequestSchema 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.putCommandExecutor.StartAsync(preferredDispatchConcurrency, cancellationToken),
                    this.getCommandExecutor.StartAsync(preferredDispatchConcurrency, cancellationToken)).ConfigureAwait(false);
            }

            public async Task StopAsync(CancellationToken cancellationToken = default)
            {
                await Task.WhenAll(
                    this.putCommandExecutor.StopAsync(cancellationToken),
                    this.getCommandExecutor.StopAsync(cancellationToken)).ConfigureAwait(false);
            }

            private async Task<ExtendedResponse<PutResponseSchema>> PutInt(ExtendedRequest<PutRequestSchema> req, CancellationToken cancellationToken)
            {
                try
                {
                    ExtendedResponse<PutResponsePayload> extended = await this.PutAsync(req.Request!, req.RequestMetadata!, cancellationToken);

                    return new ExtendedResponse<PutResponseSchema>
                    {
                        Response = new PutResponseSchema
                        {
                            Schema = extended.Response.Schema,
                        },
                        ResponseMetadata = extended.ResponseMetadata,
                    };
                }
                catch (SchemaRegistryErrorException intEx)
                {
                    ExtendedResponse<PutResponseSchema> extendedResponse = ExtendedResponse<PutResponseSchema>.CreateFromResponse(new PutResponseSchema { Error = intEx.SchemaRegistryError });
                    return extendedResponse;
                }
            }

            private async Task<ExtendedResponse<GetResponseSchema>> GetInt(ExtendedRequest<GetRequestSchema> req, CancellationToken cancellationToken)
            {
                try
                {
                    ExtendedResponse<GetResponsePayload> extended = await this.GetAsync(req.Request!, req.RequestMetadata!, cancellationToken);

                    return new ExtendedResponse<GetResponseSchema>
                    {
                        Response = new GetResponseSchema
                        {
                            Schema = extended.Response.Schema,
                        },
                        ResponseMetadata = extended.ResponseMetadata,
                    };
                }
                catch (SchemaRegistryErrorException intEx)
                {
                    ExtendedResponse<GetResponseSchema> extendedResponse = ExtendedResponse<GetResponseSchema>.CreateFromResponse(new GetResponseSchema { Error = intEx.SchemaRegistryError });
                    return extendedResponse;
                }
            }

            public async ValueTask DisposeAsync()
            {
                await this.putCommandExecutor.DisposeAsync().ConfigureAwait(false);
                await this.getCommandExecutor.DisposeAsync().ConfigureAwait(false);
            }

            public async ValueTask DisposeAsync(bool disposing, CancellationToken cancellationToken = default)
            {
                await this.putCommandExecutor.DisposeAsync(disposing, cancellationToken).ConfigureAwait(false);
                await this.getCommandExecutor.DisposeAsync(disposing, cancellationToken).ConfigureAwait(false);
            }
        }

        public abstract partial class Client : IAsyncDisposable
        {
            private ApplicationContext applicationContext;
            private IMqttPubSubClient mqttClient;
            private readonly PutCommandInvoker putCommandInvoker;
            private readonly GetCommandInvoker getCommandInvoker;

            /// <summary>
            /// Construct a new instance of this client.
            /// </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 client's lifetime.
            /// </param>
            public Client(ApplicationContext applicationContext, IMqttPubSubClient mqttClient, Dictionary<string, string>? topicTokenMap = null)
            {
                this.applicationContext = applicationContext;
                this.mqttClient = mqttClient;

                this.putCommandInvoker = new PutCommandInvoker(applicationContext, mqttClient);
                this.getCommandInvoker = new GetCommandInvoker(applicationContext, mqttClient);

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

            public PutCommandInvoker PutCommandInvoker { get => this.putCommandInvoker; }

            public GetCommandInvoker GetCommandInvoker { get => this.getCommandInvoker; }

            /// <summary>
            /// Invoke a command.
            /// </summary>
            /// <param name="request">The data for this command request.</param>
            /// <param name="requestMetadata">The metadata for this command request.</param>
            /// <param name="additionalTopicTokenMap">
            /// The topic token replacement map to use in addition to the topic tokens specified in the constructor. If this map
            /// contains any keys that the topic tokens specified in the constructor also has, then values specified in this map will take precedence.
            /// </param>
            /// <param name="commandTimeout">How long the command will be available on the broker for an executor to receive.</param>
            /// <param name="cancellationToken">Cancellation token.</param>
            /// <returns>The command response.</returns>
            public RpcCallAsync<PutResponsePayload> PutAsync(PutRequestSchema request, CommandRequestMetadata? requestMetadata = null, Dictionary<string, string>? additionalTopicTokenMap = null, TimeSpan? commandTimeout = default, 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 invoking command.");
                }

                CommandRequestMetadata metadata = requestMetadata ?? new CommandRequestMetadata();
                additionalTopicTokenMap ??= new();

                Dictionary<string, string> prefixedAdditionalTopicTokenMap = new();
                foreach (string key in additionalTopicTokenMap.Keys)
                {
                    prefixedAdditionalTopicTokenMap["ex:" + key] = additionalTopicTokenMap[key];
                }

                prefixedAdditionalTopicTokenMap["invokerClientId"] = clientId;

                return new RpcCallAsync<PutResponsePayload>(this.PutInt(request, metadata, prefixedAdditionalTopicTokenMap, commandTimeout, cancellationToken), metadata.CorrelationId);
            }

            /// <summary>
            /// Invoke a command.
            /// </summary>
            /// <param name="request">The data for this command request.</param>
            /// <param name="requestMetadata">The metadata for this command request.</param>
            /// <param name="additionalTopicTokenMap">
            /// The topic token replacement map to use in addition to the topic tokens specified in the constructor. If this map
            /// contains any keys that the topic tokens specified in the constructor also has, then values specified in this map will take precedence.
            /// </param>
            /// <param name="commandTimeout">How long the command will be available on the broker for an executor to receive.</param>
            /// <param name="cancellationToken">Cancellation token.</param>
            /// <returns>The command response.</returns>
            public RpcCallAsync<GetResponsePayload> GetAsync(GetRequestSchema request, CommandRequestMetadata? requestMetadata = null, Dictionary<string, string>? additionalTopicTokenMap = null, TimeSpan? commandTimeout = default, 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 invoking command.");
                }

                CommandRequestMetadata metadata = requestMetadata ?? new CommandRequestMetadata();
                additionalTopicTokenMap ??= new();

                Dictionary<string, string> prefixedAdditionalTopicTokenMap = new();
                foreach (string key in additionalTopicTokenMap.Keys)
                {
                    prefixedAdditionalTopicTokenMap["ex:" + key] = additionalTopicTokenMap[key];
                }

                prefixedAdditionalTopicTokenMap["invokerClientId"] = clientId;

                return new RpcCallAsync<GetResponsePayload>(this.GetInt(request, metadata, prefixedAdditionalTopicTokenMap, commandTimeout, cancellationToken), metadata.CorrelationId);
            }

            /// <summary>
            /// Stop accepting telemetry for all telemetry receivers and make all command invokers unsubscribe from command topics.
            /// </summary>
            /// <param name="cancellationToken">Cancellation token.</param>
            public async Task StopAsync(CancellationToken cancellationToken = default)
            {
                await Task.WhenAll(
                    this.putCommandInvoker.StopAsync(cancellationToken),
                    this.getCommandInvoker.StopAsync(cancellationToken)).ConfigureAwait(false);
            }

            private async Task<ExtendedResponse<PutResponsePayload>> PutInt(PutRequestSchema request, CommandRequestMetadata? requestMetadata, Dictionary<string, string>? prefixedAdditionalTopicTokenMap, TimeSpan? commandTimeout, CancellationToken cancellationToken)
            {
                ExtendedResponse<PutResponseSchema> extended = await this.putCommandInvoker.InvokeCommandAsync(request, requestMetadata, prefixedAdditionalTopicTokenMap, commandTimeout, cancellationToken);

                if (extended.Response.Error != null)
                {
                    SchemaRegistryErrorException schemaRegistryErrorException = new SchemaRegistryErrorException(extended.Response.Error);
                    throw schemaRegistryErrorException;
                }
                else
                {
                    return new ExtendedResponse<PutResponsePayload>
                    {
                        Response = new PutResponsePayload
                        {
                            Schema = extended.Response.Schema.Value(),
                        },
                        ResponseMetadata = extended.ResponseMetadata,
                    };
                }
            }

            private async Task<ExtendedResponse<GetResponsePayload>> GetInt(GetRequestSchema request, CommandRequestMetadata? requestMetadata, Dictionary<string, string>? prefixedAdditionalTopicTokenMap, TimeSpan? commandTimeout, CancellationToken cancellationToken)
            {
                ExtendedResponse<GetResponseSchema> extended = await this.getCommandInvoker.InvokeCommandAsync(request, requestMetadata, prefixedAdditionalTopicTokenMap, commandTimeout, cancellationToken);

                if (extended.Response.Error != null)
                {
                    SchemaRegistryErrorException schemaRegistryErrorException = new SchemaRegistryErrorException(extended.Response.Error);
                    throw schemaRegistryErrorException;
                }
                else
                {
                    return new ExtendedResponse<GetResponsePayload>
                    {
                        Response = new GetResponsePayload
                        {
                            Schema = extended.Response.Schema.Value(),
                        },
                        ResponseMetadata = extended.ResponseMetadata,
                    };
                }
            }

            public async ValueTask DisposeAsync()
            {
                await this.putCommandInvoker.DisposeAsync().ConfigureAwait(false);
                await this.getCommandInvoker.DisposeAsync().ConfigureAwait(false);
            }

            public async ValueTask DisposeAsync(bool disposing, CancellationToken cancellationToken = default)
            {
                await this.putCommandInvoker.DisposeAsync(disposing, cancellationToken).ConfigureAwait(false);
                await this.getCommandInvoker.DisposeAsync(disposing, cancellationToken).ConfigureAwait(false);
            }
        }
    }
}
