package ludo

import (
	"errors"
	"fmt"
	redismgr "server/db/redis"
	"server/msg"
	"strings"
)

// 判断是否已存在选择的阵营
func IsMatchColor(room_info *msg.RoomInfo, select_color msg.RoleType) bool {
	for c := range room_info.Colors {
		if room_info.Colors[c].MColor == select_color {
			return false
		}
	}
	return true
}
func AddRoom(room *msg.RoomInfo) {
	gameConfig.mu.Lock()
	defer gameConfig.mu.Unlock()
	gameConfig.RoomMap[room.Id] = room
}

func RemoveRoom(roomID int32) {
	gameConfig.mu.Lock()
	defer gameConfig.mu.Unlock()
	delete(gameConfig.RoomMap, roomID)
}

func GetRoom(roomID int32) *msg.RoomInfo {
	gameConfig.mu.RLock()
	defer gameConfig.mu.RUnlock()
	return gameConfig.RoomMap[roomID]
}

func GetRoomsByType(roomType msg.RoomType) []*msg.RoomInfo {
	gameConfig.mu.RLock()
	defer gameConfig.mu.RUnlock()

	var result []*msg.RoomInfo
	for _, room := range gameConfig.RoomMap {
		if room.RoomType == roomType {
			result = append(result, room)
		}
	}
	return result
}

func GetRoomsByLevel(matchInfo *msg.MatchLudo, roomStatus msg.RoomStatus) []*msg.RoomInfo {
	gameConfig.mu.Lock()
	defer gameConfig.mu.Unlock()

	fmt.Printf("RoomMap: %+v\n", gameConfig.RoomMap) // 打印 RoomMap 内容
	fmt.Printf("Query: roomType=%v, roomLevel=%v, roomStatus=%v, color=%v\n",
		matchInfo.SelectRoomType, matchInfo.RoomLevel, roomStatus, matchInfo.SelectColor)

	var result []*msg.RoomInfo
	for _, room := range gameConfig.RoomMap {
		fmt.Printf("Checking room: %+v\n", room) // 打印每个 room 的信息
		if room.RoomType == matchInfo.SelectRoomType &&
			room.RoomLevel == matchInfo.RoomLevel &&
			room.RoomStatus == roomStatus &&
			IsMatchColor(room, matchInfo.SelectColor) {
			result = append(result, room)
		}
	}
	return result
}

func CreateRoom(matchInfo *msg.MatchLudo, userId string) (*msg.RoomInfo, error) {
	userInfo, err_info := redismgr.GetUserInfoFromRedis(userId)
	if err_info != nil {
		return nil, errors.New("没在Redis找到该玩家 :" + userId)
	}
	// 生成房间ID（不加锁）
	roomId := generateRoomID()
	AddWaitRoomList(roomId)
	newRoom := &msg.RoomInfo{
		Id:         roomId,
		RoomLevel:  int32(matchInfo.RoomLevel),
		RoomType:   matchInfo.SelectRoomType,
		RoomMode:   msg.RoomMode_WAN_JIA, //设置为玩家pvp模式
		RoomStatus: msg.RoomStatus_AWAIT,
		Colors: []*msg.ColorData{
			{
				MId:        userId,
				MColor:     matchInfo.SelectColor, //所属阵营
				IsKick:     false,                 //是否被踢
				IsFinish:   false,                 //是否完成了比赛
				TimeOutNum: 0,                     //超时次数
				MName:      userInfo.Name,         //玩家名字
				MHead:      userInfo.MHead,        //头像
				RankNum:    0,                     //本局游戏的名次
				MCoin:      userInfo.MCoin,        //玩家拥有的金币
			},
		},
	}
	user_agent := getAgentByUserId(userId)
	if user_agent == nil {
		return nil, errors.New("getAgentByUserId 失败 :" + userId)
	}
	user_agent.SetUserData(&msg.UserInfo{
		UserId: userInfo.UserId,
		Name:   userInfo.Name,
		MCoin:  userInfo.MCoin,
		MHead:  userInfo.MHead,
		RoomId: roomId,
	})
	gameConfig.mu.Lock()
	defer gameConfig.mu.Unlock()
	gameConfig.RoomMap[newRoom.Id] = newRoom
	return newRoom, nil
}

func JoinRoom(room *msg.RoomInfo, matchInfo *msg.MatchLudo, userId string) (bool, error) {

	isRobot := strings.Contains(userId, "robot")
	var userInfo *msg.UserInfo = nil
	var err_info error = nil
	if isRobot {
		userInfo, err_info = getNewRobotPlayer(userId, room.Id)
	} else {
		userInfo, err_info = redismgr.GetUserInfoFromRedis(userId)
	}

	if err_info != nil {
		return false, errors.New("not find user at JoinRoom time ")
	}

	if !isRobot {

		user_agent := getAgentByUserId(userId)

		if user_agent == nil {
			return false, errors.New("not find user ")
		}

		ud := &msg.UserInfo{
			UserId: userInfo.UserId,
			Name:   userInfo.Name,
			MCoin:  userInfo.MCoin,
			MHead:  userInfo.MHead,
			RoomId: room.Id,
		}

		redismgr.SaveUserInfoToRedis(ud)

		user_agent.SetUserData(ud)
	}

	room.Colors = append(room.Colors, &msg.ColorData{
		MId:        userId,
		MColor:     matchInfo.SelectColor, //所属阵营
		IsKick:     false,                 //是否被踢
		IsFinish:   false,                 //是否完成了比赛
		TimeOutNum: 0,                     //超时次数
		MName:      userInfo.Name,         //玩家名字
		MHead:      userInfo.MHead,        //头像
		RankNum:    0,                     //本局游戏的名次
		MCoin:      userInfo.MCoin,        //玩家拥有的金币
	})

	isFullPlayer := false

	if room.RoomType == msg.RoomType_SHUANG_REN { //说明是两人的房间
		isFullPlayer = len(room.Colors) == 2
	} else if room.RoomType == msg.RoomType_SIREN_REN { //说明是四人的房间
		isFullPlayer = len(room.Colors) == 4
	}
	return isFullPlayer, nil
}

func generateRoomID() int32 {
	gameConfig.mu.RLock()
	defer gameConfig.mu.RUnlock()
	return int32(len(gameConfig.RoomMap) + 1)
}

func getPlayerCount(room_info *msg.RoomInfo) int {
	if room_info.RoomType == msg.RoomType_SHUANG_REN {
		return 2
	}
	return 4
}

func setPlayersRoomId(room_info *msg.RoomInfo) {
	for i := range room_info.Colors {
		user_id := room_info.Colors[i].MId
		user_agent := getAgentByUserId(user_id)
		if user_agent != nil {
			user_agent.SetUserData(&msg.UserInfo{})
		}
	}
}

func initRoles(room_info *msg.RoomInfo) {
	for i := range room_info.Colors {
		color_data := room_info.Colors[i]
		color := color_data.MColor
		for i := range 4 {
			room_info.Roles = append(room_info.Roles, &msg.RoleData{
				MColor:   color,
				MSeat:    int32(i + 1),
				MId:      fmt.Sprintf("%d_%d", color, i),
				MCurRoad: msg.RoadType_HOME,
			})
		}

	}
}

func setFirstColor(room_info *msg.RoomInfo) {
	// if room_info.RoomType == msg.RoomType_SHUANG_REN {
	// 	room_info.CurRoundColor =
	// }
	room_info.CurRoundColor = room_info.Colors[0].MColor
}

func getCurColorEventKey(room_info *msg.RoomInfo) string {
	return fmt.Sprintf("%d_%s", room_info.Id, room_info.CurRoundColor)
}
