using Fantasy;
using Fantasy.Async;
using Fantasy.Entitas.Interface;

namespace NB.Map;

public class MapRoomDestroySystem : DestroySystem<MapRoom>
{
    protected override void Destroy(MapRoom self)
    {
        self.Map = 0;
        self.Password = string.Empty;
        self.CreateTime = 0;
        self.Owner = 0;
        self.Units.Clear();
    }
}

public static class MapRoomSystem
{
    public static async FTask<uint> Enter(this MapRoom self, MapUnit unit)
    {
        self.Units.TryAdd(unit.Id, unit);

        var notifyMessage = new Map2C_RoleEnterRoomNotify()
        {
            Info = unit.ToMapUnitInfo(),
        };

        foreach (var (_, roomUnit) in self.Units)
        {
            // if (roomUnit.Id == unit.Id) continue;
            // 同步其他客户端
            self.Scene.NetworkMessagingComponent.SendInnerRoute(roomUnit.GateRouteId, notifyMessage);
        }

        await FTask.CompletedTask;
        return ErrorCode.Successful;
    }

    public static async FTask Exit(this MapRoom self, long id)
    {
        self.Units.Remove(id);
        await FTask.CompletedTask;
    }

    public static List<MapUnitInfo> ToMapUnitInfo(this MapRoom self)
    {
        List<MapUnitInfo> ret = new List<MapUnitInfo>();
        foreach (var (_, unit) in self.Units)
        {
            ret.Add(unit.ToMapUnitInfo());
        }

        return ret;
    }
}