using System.Diagnostics;
using Fantasy;
using Fantasy.Async;
using Fantasy.Network;
using Fantasy.Network.Interface;
using Fantasy.PacketParser;

namespace NB.Gate;

public class S2G_ChatMessageHandler : Route<Scene, S2G_ChatMessage>
{
    protected override async FTask Run(Scene scene, S2G_ChatMessage message)
    {
        var chatMessage = new S2C_Message()
        {
            Message = message.Message,
        };
        var idList = message.IdList;
        bool isAll = !(idList != null && idList.Count > 0);

        var gateUnitManage = scene.GetComponent<GateUnitManageComponent>();

        if (isAll)
        {
            foreach (var session in gateUnitManage.ForEachUnitSession())
            {
                session.Send(chatMessage);
            }
        }
        else
        {
            if (idList == null) return;
            foreach (var (_, gateUnit) in gateUnitManage.Units)
            {
                if (gateUnit.AccountID > 0 && idList.Contains(gateUnit.AccountID))
                {
                    Session session = gateUnit.Session;
                    if (session != null)
                    {
                        session.Send(chatMessage);
                    }
                }
            }
        }


        await FTask.CompletedTask;
    }
}