using Noctalk.Shared.Chat.Encryption;

namespace Noctalk_client.Client.Chat;

public sealed class Chat_memory_store
{
    private readonly object messageLock = new();
    private readonly Dictionary<Guid, List<Chat_memory_message>> messagesByConversation = [];

    public void Chat__message__add(Guid The_conversation_guid, Chat_memory_message The_message)
    {
        lock (messageLock)
        {
            if (!messagesByConversation.TryGetValue(The_conversation_guid, out List<Chat_memory_message>? messages))
            {
                messages = [];
                messagesByConversation[The_conversation_guid] = messages;
            }

            messages.Add(The_message);
        }
    }

    public IReadOnlyList<Chat_memory_message> Chat__messages__get(Guid The_conversation_guid)
    {
        lock (messageLock)
        {
            return messagesByConversation.TryGetValue(The_conversation_guid, out List<Chat_memory_message>? messages)
                ? messages.ToList()
                : [];
        }
    }

    public void Chat__messages__clear(Guid The_conversation_guid)
    {
        lock (messageLock)
        {
            messagesByConversation.Remove(The_conversation_guid);
        }
    }

    public void Chat__messages__update_outgoing_delivery(Guid The_conversation_guid, enum__Message_delivery The_message_delivery, IReadOnlyCollection<Chat_memory_message> The_messages_to_exclude)
    {
        lock (messageLock)
        {
            if (The_message_delivery is enum__Message_delivery.None or enum__Message_delivery.Delivered_to_server or enum__Message_delivery.Failed_to_send
                || !messagesByConversation.TryGetValue(The_conversation_guid, out List<Chat_memory_message>? messages))
            {
                return;
            }

            foreach (Chat_memory_message message in messages)
            {
                if (!message.Flag__local || The_messages_to_exclude.Contains(message))
                {
                    continue;
                }

                if (message.Message_delivery is enum__Message_delivery.None or enum__Message_delivery.Failed_to_send)
                {
                    continue;
                }

                if (The_message_delivery > message.Message_delivery)
                {
                    message.Message_delivery = The_message_delivery;
                }
            }
        }
    }
}
