using Fantasy;
using Fantasy.Async;

namespace NB.Map;

public static class MapUnitManageComponentSystem
{
    #region 上线下线

    /// <summary>
    /// 玩家上线
    /// </summary>
    /// <param name="self"></param>
    /// <param name="scene"></param>
    /// <param name="accountId"></param>
    /// <param name="gateRouteId"></param>
    public static async FTask<MapUnit?> Online(this MapUnitManageComponent self, Scene scene,
        long accountId,
        long gateRouteId)
    {
        if (!self.TryGet(accountId, out var unit))
        {
            unit = MapUnitFactory.Create(scene, accountId);
            self.Add(unit);
        }

        if (unit != null)
        {
            unit.GateRouteId = gateRouteId;
        }

        await FTask.CompletedTask;
        return unit;
    }

    public static async FTask Offline(this MapUnitManageComponent self, Scene scene, long accountId, long gateRouteId)
    {
        if (self.TryGet(accountId, out var unit) && unit != null)
        {
            if (unit.GateRouteId == gateRouteId)
            {
                self.Remove(accountId); //如果当前网关和下线的网关一致
            }
        }

        await FTask.CompletedTask;
    }

    #endregion

    #region 获取&移除

    public static void Add(this MapUnitManageComponent self, MapUnit unit)
    {
        self.Units.Add(unit.Id, unit);
    }

    public static MapUnit? Get(this MapUnitManageComponent self, long accountId)
    {
        return self.Units.GetValueOrDefault(accountId);
    }

    public static bool TryGet(this MapUnitManageComponent self, long accountId, out MapUnit? unit)
    {
        return self.Units.TryGetValue(accountId, out unit);
    }

    public static void Remove(this MapUnitManageComponent self, long accountId, bool isDispose = true)
    {
        if (!self.Units.Remove(accountId, out var account))
        {
            return;
        }

        if (!isDispose)
        {
            return;
        }

        account.Dispose();
    }

    #endregion
}