{%- import "cloudevents.jinja.include" as cloudEvents -%}
{%- import "kafka.jinja.include" as kafka -%}
{%- import "util.jinja.include" as util -%}
{{ util.CommonFileHeader() }}
{%- set messagegroups = root.messagegroups %}
{%- set uses_cloudevents_message = (root | exists("envelope","CloudEvents/1.0")) %}
{%- set uses_kafka_message = (root | exists( "protocol", "kafka")) %}
{%- set uses_kafka_endpoint = (root | exists("protocol", "kafka")) %}

#nullable enable

using CloudNative.CloudEvents;
using CloudNative.CloudEvents.SystemTextJson;
using Confluent.Kafka;

{% for messagegroupid, messagegroup in messagegroups.items() -%}
{%- set groupname = messagegroupid | pascal -%}
namespace {{ groupname | concat_namespace(project_name) | pascal }}
{
    {%- set class_name = (groupname | strip_namespace) + "EventFactory" %}
    /// <summary>
    /// Factory class to create Confluent Kafka message for the messages declared in the `{{ messagegroupid }}` message group.
    /// </summary>
    public partial class {{ class_name }}
    {
        private const string cePrefix = "ce_";
        private const string applicationOctetStream = "application/octet-stream";
        private delegate byte[] Serialize<T>(T data, string contentType);
        private static CloudEventFormatter defaultFormatter = new JsonEventFormatter();

        {%- 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 == "kafka" -%}
        {%- set options = endpoint.protocoloptions -%}
        {%- set endpoints = endpoint.endpoints %}
        {%- macro createforbody(class_name, endpoints, options) -%}
            if (bootstrapServers == null || bootstrapServers.Length == 0)
            {
                throw new ArgumentNullException(nameof(bootstrapServers));
            }
            var config = new ProducerConfig
            {
                BootstrapServers = string.Join(",", bootstrapServers?.Select(uri => uri.AbsoluteUri))
            };
            return new ProducerBuilder<byte[], byte[]>(config).Build();
        {%- endmacro %}
        
        /// <summary>
        /// Create a new instance for the {{ endpointid }} endpoint.
        /// </summary>
        /// <returns>A new instance of the IProducer&lt;byte[], byte[]&gt;.</returns>
        public static IProducer<byte[], byte[]> CreateFor{{ endpointid | pascal | strip_namespace }}(Uri[]? bootstrapServers) 
        {   
            {{ createforbody(class_name, endpoints, options) }}
        }
        {%- endif -%}
        {%- endif -%}
        {%- endfor -%}
        {% endif %}

        /// <summary>
        /// Create an instance for the specified message.
        /// </summary>
        /// <typeparam name="T">The type of the message data.</typeparam>
        /// <param name="cloudEvent">The CloudEvent instance to use for the message.</param>
        /// <param name="data">The message data.</param>
        /// <param name="contentType">The content type of the message data.</param>
        /// <param name="bodySerializer">The serializer to use for the message data.</param>
        /// <param name="formatter">The CloudEvent formatter to use for the message.</param>
        /// <param name="kafkaKey">Optional Kafka message key.</param>
        /// <param name="kafkaPartition">Optional Kafka partition.</param>
        /// <param name="kafkaHeaders">Optional Kafka headers to add.</param>
        /// <returns>A `Message&lt;byte[], byte[]&gt;` instance for the specified message.</returns>
        private static Message<byte[], byte[]> CreateMessage<T>(CloudEvent? cloudEvent, T data, string contentType, Serialize<T>? bodySerializer = null, CloudEventFormatter? formatter = null, byte[]? kafkaKey = null, int? kafkaPartition = null, Dictionary<string, string>? kafkaHeaders = null) where T : notnull
        {
            if (formatter == null)
            {
                bool isRawBytes = typeof(T) == typeof(byte[]);
                if (bodySerializer == null && !isRawBytes)
                {
                    throw new ArgumentNullException(nameof(bodySerializer));
                }
                var eventPayload = bodySerializer == null ? (byte[])(object)data : bodySerializer(data, contentType);
                var message = new Message<byte[], byte[]>
                {
                    Value = eventPayload,
                    Key = kafkaKey,
                    Headers = new Headers() {
                        new Header("content-type", System.Text.Encoding.UTF8.GetBytes(contentType))
                    }
                };
                if (kafkaHeaders != null)
                {
                    foreach (var header in kafkaHeaders)
                    {
                        message.Headers.Add(header.Key, System.Text.Encoding.UTF8.GetBytes(header.Value));
                    }
                }
                if (cloudEvent != null)
                {
                    foreach (var attr in cloudEvent.GetPopulatedAttributes())
                    {
                        var attrValue = attr.Value switch
                        {
                            string s => s,
                            Uri u => u.ToString(),
                            _ => attr.Value.ToString()
                        };
                        if ( attrValue != null)
                        {
                            message.Headers.Add(cePrefix + attr.Key.Name, System.Text.Encoding.UTF8.GetBytes(attrValue));
                        }
                    }
                }
                return message;
            }
            else
            {
                if (cloudEvent == null)
                {
                    throw new ArgumentNullException(nameof(cloudEvent));
                }
                if (formatter is CloudNative.CloudEvents.SystemTextJson.JsonEventFormatter && 
                    new System.Net.Mime.ContentType(contentType).MediaType == System.Net.Mime.MediaTypeNames.Application.Json)
                {
                    cloudEvent.Data = data;
                }
                else
                {
                    bool isRawBytes = typeof(T) == typeof(byte[]);
                    if (bodySerializer == null && !isRawBytes)
                    {
                        throw new ArgumentNullException(nameof(bodySerializer));
                    }
                    cloudEvent.Data = bodySerializer == null ? data : bodySerializer(data, contentType);
                }
                var eventBody = formatter.EncodeStructuredModeMessage(cloudEvent, out var eventContentType);
                var message = new Message<byte[], byte[]>
                {
                    Value = eventBody.ToArray(),
                    Key = kafkaKey,
                    Headers = new Headers() {
                        new Header("content-type", System.Text.Encoding.UTF8.GetBytes(eventContentType.ToString()))
                    }
                };
                if (kafkaHeaders != null)
                {
                    foreach (var header in kafkaHeaders)
                    {
                        message.Headers.Add(header.Key, System.Text.Encoding.UTF8.GetBytes(header.Value));
                    }
                }
                return message;
            }
        }

        {% for messageid, message in messagegroup.messages.items() -%}
        {%- set messagename = messageid | pascal %}
        {%- set is_cloudevent = not message.envelope or message.envelope.lower().startswith("cloudevents") -%}
        {%- set isKafka = not is_cloudevent and message.envelope.lower().startswith("kafka") %}
        {%- set type_name = util.body_type(data_project_name, root, message) -%}
        {%- if is_cloudevent %}
        {%- set uriargs = cloudEvents.DeclareUriTemplateArguments(message) -%}
        {%- elif isKafka %}
        {%- set uriargs = kafka.DeclareUriTemplateArguments(message) -%}
        {%- endif %}
        /// <summary>
        /// Create a `Message&lt;byte[], byte[]&gt;` instance for 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 is_cloudevent %}
        /// <param name="formatter">The CloudEvent formatter to use for structured mode, e.g. JsonEventFormatter.</param>
        {%- endif %}
        /// <returns>A `Message&lt;byte[], byte[]&gt;` instance for the {{ messagename }} message.</returns>
        public static Message<byte[], byte[]> Create{{ messagename | strip_namespace }}Message(
        {{ type_name }} data
        {%- if uriargs -%}
        {{- uriargs -}}
        {%- endif -%}
        {%- if is_cloudevent 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 is_cloudevent %}, CloudEventFormatter? formatter = null{% endif %})
        {
            {%- if "protocolmetadata" in message %}
            {%- if "key" in message.protocolmetadata and "value" in message.protocolmetadata.key %}
            byte[]? kafkaKey = System.Text.Encoding.UTF8.GetBytes("{{ message.protocolmetadata.key.value }}");
            {%- else %}
            byte[]? kafkaKey = null;
            {%- endif %}
            {%- if "partition" in message.protocolmetadata and "value" in message.protocolmetadata.partition %}
            int? kafkaPartition = {{ message.protocolmetadata.partition.value }};
            {%- else %}
            int? kafkaPartition = null;
            {%- endif %}
            {%- if "headers" in message.protocolmetadata and "properties" in message.protocolmetadata.headers %}
            var kafkaHeaders = new Dictionary<string, string>
            {
                {%- for headername, header in message.protocolmetadata.headers.properties.items() %}
                {%- if "value" in header %}
                { "{{ headername }}", "{{ header.value }}" },
                {%- endif %}
                {%- endfor %}
            };
            {%- else %}
            Dictionary<string, string>? kafkaHeaders = null;
            {%- endif %}
            {%- else %}
            byte[]? kafkaKey = null;
            int? kafkaPartition = null;
            Dictionary<string, string>? kafkaHeaders = null;
            {%- endif %}
            {% if type_name != "byte[]" %}
            Serialize<{{ type_name }}>? bodySerializer = (formatter != null) ? null : ({{ type_name }} data, string contentType) => {
                return data.ToByteArray(contentType);
            };
            {%- if is_cloudevent %}
            {{ cloudEvents.DeclareCloudNativeCloudEvent("cloudEvent", message) | indent(12) }}
            return CreateMessage(cloudEvent, data, contentType, bodySerializer, formatter, kafkaKey, kafkaPartition, kafkaHeaders);
            {%- elif isKafka %}
            return CreateMessage(null, data, contentType, bodySerializer, null, kafkaKey, kafkaPartition, kafkaHeaders);
            {%- endif %}
            {% else %}
            {%- if is_cloudevent %}
            {{ cloudEvents.DeclareCloudNativeCloudEvent("cloudEvent", message) | indent(12) }}
            return CreateMessage(cloudEvent, data, contentType, null, formatter, kafkaKey, kafkaPartition, kafkaHeaders);
            {%- elif isKafka %}
            return CreateMessage(null, data, contentType, null, null, kafkaKey, kafkaPartition, kafkaHeaders);
            {%- endif %}
            {% endif %}
            
        }
        {% endfor %}
    }
}
{% endfor -%}
