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

namespace NB.Map.Inner;

public class G2Map_EnterRoomRequestHandler : RouteRPC<Scene, G2Map_EnterRoomRequest, Map2G_EnterRoomResponse>
{
    protected override async FTask Run(Scene entity, G2Map_EnterRoomRequest request, Map2G_EnterRoomResponse 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;
        }


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

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

        if (mapUnit.MapId != room.Map)
        {
            //切换地图
            response.ErrorCode = await mapUnit.EnterMap(mapUnit.MapId);
            if (response.ErrorCode != 0)
            {
                return;
            }
        }
    
        

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