using Fantasy;
using Fantasy.Async;
using Fantasy.Entitas;
using Fantasy.Entitas.Interface;
using Fantasy.Helper;
using NB.Game;

namespace NB.Chat;

public class MailManageComponentDestroySystem : DestroySystem<MailManageComponent>
{
    protected override void Destroy(MailManageComponent self)
    {
        foreach (var (_, conversation) in self.Conversations)
        {
            conversation.Dispose();
        }

        self.Conversations.Clear();
    }
}

public static class MailManageComponentSystem
{
    public static async FTask DeleteConversation(this MailManageComponent self, long selfId, long otherId)
    {
        var firstId = selfId;
        var secondId = otherId;
        if (otherId < selfId)
        {
            firstId = otherId;
            secondId = selfId;
        }

        var key = $"{firstId}-{secondId}";

        if (self.Conversations.Remove(key, out var conversation))
        {
            await MailConversationHelper.DeleteDataBase(conversation.Scene, conversation.Id);
            conversation.Dispose();
        }
    }

    public static async FTask<MailConversation?> GetConversation(this MailManageComponent self, long selfId,
        long otherId)
    {
        var firstId = selfId;
        var secondId = otherId;
        if (otherId < selfId)
        {
            firstId = otherId;
            secondId = selfId;
        }

        var key = $"{firstId}-{secondId}";
        if (!self.Conversations.TryGetValue(key, out var conversation))
        {
            //检查数据库中是否存在
            conversation = await MailConversationHelper.LoadDataBase(self.Scene, firstId, secondId);
            if (conversation == null)
            {
                //检查id是否合法
                var roleInfo = await CacheHandler.GetPlayerBasicCacheInfo(self.Scene, otherId);
                if (roleInfo == null)
                {
                    return null;
                }

                conversation = Entity.Create<MailConversation>(self.Scene, true, true);

                conversation.FirstId = firstId;
                conversation.SecondId = secondId;

                conversation.Key = key;
                await conversation.Save(false);
            }

            self.Conversations.Add(key, conversation);
        }

        return conversation;
    }

    public static async FTask<List<MailConversation>> GetConversations(this MailManageComponent self, long id)
    {
        List<MailConversation> players =
            await self.Scene.World.DataBase.QueryByPageOrderBy<MailConversation>(
                d => d.FirstId == id || d.SecondId == id, 1, 50,
                d => d.UpdateTime);

        return players;
    }
}