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

namespace NB.Map;

public class C2Map_CreateRoomRequestHandler : RouteRPC<MapUnit, C2Map_CreateRoomRequest, Map2C_CreateRoomResponse>
{
    protected override async FTask Run(MapUnit entity, C2Map_CreateRoomRequest request,
        Map2C_CreateRoomResponse response,
        Action reply)
    {
        if (entity.MapId != request.MapId)
        {
            response.ErrorCode = ErrorCode.MapCreateRoomNotEnter;
            return;
        }

        var roomManageComponent = entity.Scene.GetComponent<RoomManageComponent>();
        if (roomManageComponent == null)
        {
            response.ErrorCode = ErrorCode.ErrServer;
            return;
        }

        var room = roomManageComponent.Create(entity.Id);

        if (room == null)
        {
            response.ErrorCode = ErrorCode.MapCreateRoomMax;
            return;
        }
        
        Log.Info(
            $"创建房间=== sId={entity.Scene.SceneConfigId} map:{request.MapId} id={room.RoomId} code={room.Code}");
        
        response.RoomCode = room.Code;
        
        await FTask.CompletedTask;
    }
}