using Fantasy;
using Fantasy.Async;
using Fantasy.Network;
using Fantasy.Platform.Net;
using NB.Chat;
using NB.Game;

// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract

namespace NB.Gate;

public static class GateLoginHelper
{
    #region 上线

    /// <summary>
    /// 网关通知其他服务器上线
    /// </summary>
    /// <param name="gateUnit"></param>
    public static async FTask<uint> Online(GateUnit gateUnit)
    {
        if (gateUnit == null)
        {
            return ErrorCode.ErrArgs;
        }

        Session session = gateUnit.Session;
        if (session == null)
        {
            return ErrorCode.ErrArgs;
        }

        var gateUnitSessionComponent = session.GetComponent<GateUnitSessionComponent>();
        if (gateUnitSessionComponent == null)
        {
            gateUnitSessionComponent = session.AddComponent<GateUnitSessionComponent>();
        }

        var routeComponent = session.GetComponent<RouteComponent>();
        if (routeComponent == null)
        {
            session.AddComponent<RouteComponent>();
        }

        gateUnitSessionComponent.AccountID = gateUnit.AccountID;
        gateUnitSessionComponent.SessionId = session.RuntimeId;

        return await gateUnit.Online(RouteType.GameRoute, RouteType.SocialRoute, RouteType.MapRoute);
    }

    #endregion

    #region 下线

    /// <summary>
    /// 网关通知其他服务器下线
    /// </summary>
    /// <param name="gateUnit"></param>
    /// <param name="sessionId"></param>
    public static async FTask<uint> Offline(GateUnit gateUnit, long sessionId)
    {
        //通知服务器下线
        Log.Info($"断线的session id={sessionId}");
        var ret = await gateUnit.Offline(sessionId, RouteType.GameRoute, RouteType.SocialRoute, RouteType.MapRoute);
        return ret;
    }

    #endregion
}