namespace Noctalk_client.Client.Chat;

public sealed class Outgoing_send_queue
{
    private readonly object queueLock = new();
    private readonly List<Outgoing_send_queue_item> queuedItems = [];
    private long nextCreationOrder;

    public void Enqueue(Guid Conversation_guid, Chat_memory_message Local_message, Noctalk.Shared.Chat.Api.Json.Chat_client__to__server.Poll.Message Encrypted_payload)
    {
        lock (queueLock)
        {
            queuedItems.Add(new Outgoing_send_queue_item
            {
                conversation__guid = Conversation_guid,
                Local_message = Local_message,
                Encrypted_payload = Encrypted_payload,
                Creation_order = ++nextCreationOrder
            });
        }
    }

    public List<Outgoing_send_queue_item> Dequeue_for_conversations(IReadOnlySet<Guid> Conversation_guids)
    {
        lock (queueLock)
        {
            List<Outgoing_send_queue_item> items = queuedItems
                .Where(The_item => Conversation_guids.Contains(The_item.conversation__guid))
                .OrderBy(The_item => The_item.Creation_order)
                .ToList();

            if (items.Count == 0)
            {
                return [];
            }

            queuedItems.RemoveAll(The_item => Conversation_guids.Contains(The_item.conversation__guid));
            return items;
        }
    }

}
