{%- import "cloudevents.jinja.include" as cloudEvents -%}
{%- import "amqp.jinja.include" as amqp -%}
{%- import "util.jinja.include" as util -%}
{{ util.CommonFileHeader() }}
{%- set messagegroups = root.messagegroups %}
{%- set uses_cloudevents_message = (root | exists("envelope","CloudEvents/1.0")) %}
{%- set uses_amqp_message = amqp.uses_amqp_protocol(root) %}
{%- set uses_amqp_endpoint = amqp.uses_amqp_endpoint(root) %}
// This code was generated by the xRegistry tool.
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.

#nullable enable

using CloudNative.CloudEvents;
using CloudNative.CloudEvents.SystemTextJson;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Producer;

{% for messagegroupid, messagegroup in messagegroups.items() -%}
{%- set groupname = messagegroupid  | pascal -%}
namespace {{ groupname | concat_namespace(project_name) | pascal }}
{
    {%- set class_name = ( groupname | strip_namespace )+"Producer" %}
    /// <summary>
    /// Producer class to send events in the `{{ messagegroupid }}` message group.
    /// </summary>
    public partial class {{ class_name }}
    {
        {%- if root.endpoints -%} 
        {%- for endpointid, endpoint in root.endpoints.items() -%}
        {%- if endpoint.usage and "producer" in endpoint.usage -%}
        {%- set protocol = endpoint.protocol | lower -%}
        {%- if protocol == "amqp" -%}
        {%- set options = endpoint.protocoloptions -%}
        {%- set endpoints = endpoint.endpoints %}
        {%- macro createforbody(class_name, endpoints, options) -%}
            if ( fullyQualifiedNamespace == null )
            {
                {%- if endpoints %}
                fullyQualifiedNamespace = "{{ endpoints[0].uri }}";
                {%- else %}
                throw new ArgumentNullException(nameof(fullyQualifiedNamespace));
                {%- endif %}
            }
            if ( eventHubName == null )
            {
                {%- if options and 'node' in options %}
                eventHubName = "{{ options['node'] }}";
                {%- else %}
                throw new ArgumentNullException(nameof(eventHubName));
                {%- endif %}
            }
            var client = new EventHubProducerClient(fullyQualifiedNamespace, eventHubName, credential);
            return {{ class_name }}(client);
        {%- endmacro %}
        
        /// <summary>
        /// Create a new instance of the `EventHubProducerClient` for the {{ endpointid }} endpoint.
        /// </summary>
        /// <param name="credential">The Azure credential to use for authentication.</param>
        /// <param name="fullyQualifiedNamespace">The fully qualified namespace of the Event Hub.</param>
        /// <param name="eventHubName">The name of the Event Hub.</param>
        /// <returns>A new instance of the `EventHubProducerClient`.</returns>
        public static {{ class_name }} CreateFor{{ endpointid | pascal | strip_namespace }}(TokenCredential credential, string? fullyQualifiedNamespace = null, string? eventHubName = null) 
        {   
            {{ createforbody(class_name, endpoints, options) }}
        }

        /// <summary>
        /// Create a new instance of the `EventHubProducerClient` for the {{ endpointid }} endpoint.
        /// </summary>
        /// <param name="credential">The Azure credential to use for authentication.</param>
        /// <param name="fullyQualifiedNamespace">The fully qualified namespace of the Event Hub.</param>
        /// <param name="eventHubName">The name of the Event Hub.</param>
        /// <returns>A new instance of the `EventHubProducerClient`.</returns>
        public static {{ class_name }} CreateFor{{ endpointid | pascal | strip_namespace }}(AzureNamedKeyCredential credential, string? fullyQualifiedNamespace = null, string? eventHubName = null) 
        {       
            {{ createforbody(class_name, endpoints, options) }}
        }

        /// <summary>
        /// Create a new instance of the `EventHubProducerClient` for the {{ endpointid }} endpoint.
        /// </summary>
        /// <param name="credential">The Azure credential to use for authentication.</param>
        /// <param name="fullyQualifiedNamespace">The fully qualified namespace of the Event Hub.</param>
        /// <param name="eventHubName">The name of the Event Hub.</param>
        /// <returns>A new instance of the `EventHubProducerClient`.</returns>
        public static {{ class_name }} CreateFor{{ endpointid | pascal | strip_namespace }}(AzureSasCredential credential, string? fullyQualifiedNamespace = null, string? eventHubName = null) 
        {       
            {{ createforbody(class_name, endpoints, options) }}
        }
        {%- endif -%}
        {%- endif -%}
        {%- endfor -%}
        {% endif %}

        /// <summary>
        /// Constructor
        /// </summary>
        public {{ class_name }}(EventHubProducerClient client)
        {
            this.Client = client;
        }

        /// <summary>
        /// Event Hub producer client
        /// </summary>
        public EventHubProducerClient Client
        {
            get; private set;
        }

        {% for messageid, message in messagegroup.messages.items() -%}
        {%- set messagename = messageid | pascal %}
        {%- set isCloudEvent = cloudEvents.isCloudEvent(message) %}
        {%- set is_amqp = amqp.is_amqp(message) %}
        {%- set type_name = util.body_type(data_project_name, root, message) %}
        {%- if isCloudEvent %}
        {%- set uriargs = cloudEvents.DeclareUriTemplateArguments(message) -%}
        {%- elif is_amqp %}
        {%- set uriargs = amqp.DeclareUriTemplateArguments(message) -%}
        {%- endif %}
        /// <summary>
        /// Publish the `{{ messagename }}` event
        {%- if message.description %}
        /// Event description: "{{ message.description }}"
        {%- endif %}
        /// </summary>
        /// <param name="data">The event data object.</param>
        {%- if uriargs %}
        {%- for arg in uriargs.split(',') if arg.strip() %}
        {%- set splitarg = arg.strip().split(' ')%}
        /// <param name="{{ splitarg[1] }}"> URI template argument</param>
        {%- endfor %}
        {%- endif %}
        /// <param name="contentType">The desired content type of the message data.</param>
        {%- if isCloudEvent %}
        /// <param name="formatter">The CloudEvent formatter to use for structured mode, e.g. JsonEventFormatter.</param>
        {%- endif %}
        /// <returns>An `EventData` instance for the {{ messagename }} message.</returns>
        public Task Send{{ messagename | strip_namespace }}Async(
        {{ type_name }} data
        {%- if uriargs -%}
        {{- uriargs -}}
        {%- endif -%}
        {%- if isCloudEvent and "datacontenttype" in message.envelopemetadata and "value" in message.envelopemetadata["datacontenttype"] -%}
        , string contentType = "{{ message.envelopemetadata["datacontenttype"]["value"] }}"
        {%- else -%}
        , string contentType = System.Net.Mime.MediaTypeNames.Application.Json
        {%- endif %}
        {%- if isCloudEvent %}, CloudEventFormatter? formatter = null{% endif %})
        {
            var eventData = {{groupname | strip_namespace}}EventFactory.Create{{ messagename | strip_namespace }}Event(data,
                {%- if uriargs %}
                {%- for arg in uriargs.split(',') if arg.strip() %}
                {%- set splitarg = arg.strip().split(' ')%}
                {{- splitarg[1] -}},
                {%- endfor -%}
                {%- endif -%}
                contentType
                {%- if isCloudEvent %}, formatter{% endif -%}
            );
            return this.Client.SendAsync(new []{eventData});
        }

        /// <summary>
        /// Send a batch of `{{ messagename }}` events
        {%- if message.description %}
        /// Event description: "{{ message.description }}"
        {%- endif %}
        /// </summary>
        /// <param name="data">The event data objects.</param>
        {%- if uriargs %}
        {%- for arg in uriargs.split(',') if arg.strip() %}
        {%- set splitarg = arg.strip().split(' ')%}
        /// <param name="{{ splitarg[1] }}"> URI template argument</param>
        {%- endfor %}
        {%- endif %}
        /// <param name="contentType">The desired content type of the message data.</param>
        {%- if isCloudEvent %}
        /// <param name="formatter">The CloudEvent formatter to use for structured mode, e.g. JsonEventFormatter.</param>
        {%- endif %}
        /// <returns>Task object</returns>
        public async Task Send{{ messagename | strip_namespace }}BatchAsync(
        {{ type_name }}[] data
        {%- if uriargs -%}
        {{- uriargs -}}
        {%- endif -%}
        {%- if isCloudEvent and "datacontenttype" in message.envelopemetadata and "value" in message.envelopemetadata["datacontenttype"] -%}
        , string contentType = "{{ message.envelopemetadata["datacontenttype"]["value"] }}"
        {%- else -%}
        , string contentType = System.Net.Mime.MediaTypeNames.Application.Json
        {%- endif %}
        {%- if isCloudEvent %}, CloudEventFormatter? formatter = null{% endif %})
        {
            var batch = await this.Client.CreateBatchAsync();
            foreach( var record in data )
            {
                var eventData = {{groupname | strip_namespace}}EventFactory.Create{{ messagename | strip_namespace }}Event(record, 
                {%- if uriargs %}
                {%- for arg in uriargs.split(',') if arg.strip() %}
                {%- set splitarg = arg.strip().split(' ')%}
                {{- splitarg[1] -}},
                {%- endfor -%}
                {%- endif -%}
                contentType{%- if isCloudEvent %}, formatter{% endif %});
                if ( !batch.TryAdd(eventData))
                {
                    await this.Client.SendAsync(batch);
                    batch = await this.Client.CreateBatchAsync();
                    batch.TryAdd(eventData);
                }
            }
            if (batch.Count > 0)
            {
                await this.Client.SendAsync(batch);
            }
        }
        {% endfor %}
    }
}
{% endfor -%}