using System;
using System.Collections.Generic;
using Godot;
using Sfs3.Client.Core;
using Sfs3.Client.Entities;
using Sfs3.Client.Entities.Data;

public static class BuddyChatHistoryManager
{
	private static Dictionary<string, List<BuddyChatMessage>> buddyChatLists = [];
	private static Dictionary<string, int> unreadMsgCounters = [];

	public static BuddyChatMessage AddMessage(string targetBuddyName, string senderName, bool isItMe, string message)
	{
		// Initialize queue
        if (!buddyChatLists.ContainsKey(targetBuddyName))
        {
            buddyChatLists.Add(targetBuddyName, []);
            unreadMsgCounters.Add(targetBuddyName, 0);
        }

		// Add message to queue
		var chatMsg = new BuddyChatMessage(targetBuddyName, senderName, message, isItMe);

		if (buddyChatLists.TryGetValue(targetBuddyName, out List<BuddyChatMessage> list))
			list.Add(chatMsg);

        // Return chat message
        return chatMsg;
	}

	public static int IncreaseUnreadMessagesCount(string buddyName)
	{
		// Increase unread messages counter
		unreadMsgCounters[buddyName]++;

		// Return total number of unread messages
		return unreadMsgCounters[buddyName];
	}

	public static List<BuddyChatMessage> GetBuddyChatMessages(string buddyName)
	{
		buddyChatLists.TryGetValue(buddyName, out List<BuddyChatMessage> buddyChatMessages);

		return buddyChatMessages;
	}

	public static int GetUnreadMessagesCount(string buddyName)
	{
		if (unreadMsgCounters.ContainsKey(buddyName))
			return unreadMsgCounters[buddyName];

		return 0;
	}

	public static void ResetUnreadMessagesCount(string buddyName)
	{
		if (unreadMsgCounters.ContainsKey(buddyName))
			unreadMsgCounters[buddyName] = 0;
	}

    public static void ResetHistory(string buddyName)
    {
        buddyChatLists.Remove(buddyName);
        unreadMsgCounters.Remove(buddyName);
    }

    public static void ResetAllHistory()
    {
		buddyChatLists = [];
		unreadMsgCounters = [];
    }
}

/**
 * Utility class to store buddy chat message details.
 */
public class BuddyChatMessage
{
	public string Target;
	public string Sender;
	public string Message;
	public bool SentByMe;
	public DateTime Date;

	public BuddyChatMessage(string target, string sender, string message, bool sentByMe)
	{
		Target = target;
		Sender = sender;
		Message = message;
		SentByMe = sentByMe;
		Date = DateTime.Now;
	}
}
