package teen

import (
	"server/game/room"
	"sort"

	"github.com/name5566/leaf/log"
)

// 随机选一个一个玩家当庄家md
// func randomDealer(room *room.Room) {
// 	// room.SetDealerPlayer(room.Players[rand.Intn(len(room.Players))])
// 	room.SetDealerPlayer(room.GetPlayerBySitPos(SelfSitPos))
// }

// // 一共4个座位，指定需要的座位数量，且不重复的随即返回
// func randomSitPos(_ *room.Room, num int) []int {
// 	availablePos := make([]int, 4)
// 	for i := range availablePos {
// 		availablePos[i] = i
// 	}

//		// 随机选择不重复的座位号
//		sitPos := make([]int, 0, num)
//		for i := 0; i < num && len(availablePos) > 0; i++ {
//			// 随机选择一个索引
//			index := rand.Intn(len(availablePos))
//			// 将选中的座位号添加到结果中
//			sitPos = append(sitPos, availablePos[index])
//			// 从可用座位中移除已选择的座位
//			availablePos = append(availablePos[:index], availablePos[index+1:]...)
//		}
//		return sitPos
//	}
//
// 按座位获取房间的上一位玩家或者下一位玩家
func getRoomSitPos(r *room.Room, sitPos int32, num int) int32 {
	// 未弃牌的玩家按座位排序
	validSitPositions := getSortedValidSitPositions(r)
	// 当前玩家的索引
	currentPlayerIndex := -1
	for i, pos := range validSitPositions {
		if pos == sitPos {
			currentPlayerIndex = i
			break
		}
	}
	previousSitPos := validSitPositions[(currentPlayerIndex+num+len(validSitPositions))%len(validSitPositions)]
	return previousSitPos
}

// 获取当前房间有效玩家的座位，并按座位号排序
func getSortedValidSitPositions(teenPattiRoom *room.Room) []int32 {
	validSitPositions := make([]int32, 0)

	// 遍历房间玩家，筛选未弃牌玩家的座位号
	for _, player := range teenPattiRoom.Players {
		if !player.IsPacked { // 排除弃牌的玩家
			validSitPositions = append(validSitPositions, player.SitPos)
		}
	}

	// 按照座位号升序排序
	sort.Slice(validSitPositions, func(i, j int) bool {
		return validSitPositions[i] < validSitPositions[j]
	})

	return validSitPositions
}
func setNextDealerSitPos(teenPattiRoom *room.Room, currentDealerSitPos int32) {
	// 获取当前牌局所有有效的玩家坐位（按座位号排序）
	validSitPositions := getSortedValidSitPositions(teenPattiRoom)

	// 打印当前房间有效的玩家座位信息
	log.Debug("currentDealerSitPos: %v", currentDealerSitPos)

	log.Debug("Valid sit positions: %v", validSitPositions)

	// 确保至少有 2 名有效玩家，否则无法更换庄家
	if len(validSitPositions) < 2 {
		log.Debug("Not enough players to change dealer.")
		return
	}

	// 查找当前庄家的索引
	currentDealerIndex := -1
	for i, sitPos := range validSitPositions {
		if sitPos == currentDealerSitPos {
			currentDealerIndex = i
			break
		}
	}

	// 如果当前庄家不存在（找不到），默认选取座位号最小的玩家
	if currentDealerIndex == -1 {
		log.Debug("Current dealer's seat position not found, using first player as dealer.")
		currentDealerIndex = 0 // 选择第一个有效玩家作为庄家
	}

	// 获取下一个庄家（按照顺时针方向）
	nextDealerSitPos := validSitPositions[(currentDealerIndex+1)%len(validSitPositions)]

	// 设置下一个庄家
	// nextDealer := teenPattiRoom.GetPlayerBySitPos(nextDealerSitPos)
	nextDealer := teenPattiRoom.GetPlayerBySitPos(4)
	if nextDealer != nil {
		nextDealer.IsDealer = true
		log.Debug("Setting player %v (seat: %d) as dealer", nextDealer.Id, nextDealerSitPos)
	} else {
		log.Debug("Next dealer not found.")
	}
}
