package logic

import (
	log "Server-Core/Server/Base/Log"
	message "Server-Core/Server/Message"
)

const (
	roomIdMin int64 = 10000 //房间ID下限
	roomIdMax int64 = 99999 //房间ID上限
)

type RoomMgr struct {
	roomByRoomId     map[int64]*Room //房间列表
	roomIdByPlayerId map[int64]int64 //玩家ID到房间ID的一个映射

	idGenList map[int64]int64 //策划需求房间ID范围为10000-99999,则直接遍历一遍把ID占位分配好，反正也不可能一次性开十万个房间
}

func CreateRoomMgr() *RoomMgr {
	mgr := new(RoomMgr)
	mgr.roomByRoomId = make(map[int64]*Room)
	mgr.roomIdByPlayerId = make(map[int64]int64)
	mgr.idGenList = make(map[int64]int64)
	for i := roomIdMin; i <= roomIdMax; i++ {
		mgr.idGenList[i] = 0 //初始化，全部没有被占用
	}
	return mgr
}

// 获取一个未被占用的房间ID
func (mgr *RoomMgr) GetID() int64 {
	for id, status := range mgr.idGenList {
		if status == 0 {
			return id
		}
	}
	log.Error("GetID error ID is 0")
	return 0 //ID全部被用完了则返回0，一般不会这样会
}

// 设置一个ID为已使用状态
func (mgr *RoomMgr) SetIdUsed(id int64) {
	mgr.idGenList[id] = 1
}

// 设置一个ID为未使用状态
func (mgr *RoomMgr) SetIdUnUsed(id int64) {
	mgr.idGenList[id] = 0
}

// 通过房间ID获取房间对象
func (mgr *RoomMgr) GetRoomByRoomId(roomId int64) *Room {
	return mgr.roomByRoomId[roomId]
}

// 通过玩家ID获取房间ID
func (mgr *RoomMgr) GetRoomIdByPlayerId(playerId int64) int64 {
	return mgr.roomIdByPlayerId[playerId]
}

// 移除玩家到房间的映射
func (mgr *RoomMgr) RemovePlayerIdFromRoom(playerId int64) {
	delete(mgr.roomIdByPlayerId, playerId)
}

// 通过玩家ID获取准备房间对象
func (mgr *RoomMgr) GetRoomByPlayerId(PlayerId int64) *Room {
	roomId := mgr.GetRoomIdByPlayerId(PlayerId)
	room := mgr.GetRoomByRoomId(roomId)
	return room
}

func (mgr *RoomMgr) Run() {
	//遍历房间的帧同步消息
	for _, room := range mgr.roomByRoomId {
		//房间人数为0或者房间状态为结束状态则释放该房间
		if len(room.roomPlayerInfo) == 0 || room.status == 2 {
			delete(mgr.roomByRoomId, room.roomId)
			mgr.SetIdUnUsed(room.roomId)
			//释放房间做个打印
			continue
		}
		room.Run() //跑帧同步逻辑
	}
}

// 拉取所有准备房间的数据
func (mgr *RoomMgr) GetRoomList() *message.GetRoomListRsp {
	roomListRsp := &message.GetRoomListRsp{}
	for _, room := range mgr.roomByRoomId {
		log.Info("GetRoomList any Room:{%s}", room.roomId)
	}

	return roomListRsp
}
