using Fantasy;
using Fantasy.Async;
using Fantasy.Network.Interface;

namespace NB.Map.Inner;

/// <summary>
/// 请求进入地图
/// </summary>
public class G2Map_EnterMapRequestHandler : RouteRPC<Scene, G2Map_EnterMapRequest, Map2G_EnterMapResponse>
{
    protected override async FTask Run(Scene entity, G2Map_EnterMapRequest request, Map2G_EnterMapResponse response,
        Action reply)
    {
        var roomManageComponent = entity.GetComponent<RoomManageComponent>();
        if (roomManageComponent == null)
        {
            response.ErrorCode = ErrorCode.ErrServer;
            return;
        }

        var mapUnitManage = entity.GetComponent<MapUnitManageComponent>();
        if (mapUnitManage == null)
        {
            response.ErrorCode = ErrorCode.ErrServer;
            return;
        }

        var mapUnit = mapUnitManage.Get(request.AccountId);
        if (mapUnit == null)
        {
            response.ErrorCode = ErrorCode.ErrServer;
            return;
        }


        //进入地图
        response.ErrorCode = await mapUnit.EnterMap(request.MapId);
        if (response.ErrorCode != 0)
        {
            return;
        }

        // 如果没有房间代码，则只是进入地图，直接返回，不执行后续逻辑
        if (string.IsNullOrEmpty(request.RoomCode))
        {
            response.Units = [mapUnit.ToMapUnitInfo()];
            return;
        }

        RoomHelper.ParseCode(request.RoomCode, out var serviceId, out var roomId);
        if (serviceId < 1 || roomId < 1)
        {
            return;
        }

        var room = roomManageComponent.Get(roomId);
        if (room == null)
        {
            return;
        }

        response.ErrorCode = await room.Enter(mapUnit);
        response.RoomCode = room.Code;
        if (response.ErrorCode == ErrorCode.Successful)
        {
            mapUnit.RoomId = room.RoomId;
            response.Units = room.ToMapUnitInfo();
        }
    }
}