package ludo

import (
	"fmt"
	"server/console"
	"server/msg"
	"time"
)

var wait_room map[int32]time.Time = make(map[int32]time.Time)

var namesArray [10]string = [10]string{
	"Alice", "Bob", "Charlie", "David", "Eve",
	"Frank", "Grace", "Henry", "Ivy", "Jack",
}

func AddWaitRoomList(room_id int32) {
	wait_room[room_id] = time.Now()
}

func RemoveWaitRoomList(room_id int32) {
	delete(wait_room, room_id)
}

func StartMatchRobotTask() {
	// 创建每秒触发一次的定时器
	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop() // 确保退出时释放资源

	for {
		select {
		case <-ticker.C:
			Scheduling()
		}
	}
}

func Scheduling() {
	for room_id, start_time := range wait_room {
		room_info := gameConfig.RoomMap[room_id]
		if room_info == nil {
			RemoveWaitRoomList(room_id)
		} else {
			if room_info.RoomStatus != msg.RoomStatus_AWAIT {
				RemoveWaitRoomList(room_id)
			} else {
				cur_time := time.Now()
				// 计算整数秒（直接截断小数部分）
				seconds := int(cur_time.Sub(start_time).Seconds())
				fmt.Printf("Scheduling seconds %d:\n", seconds)
				if seconds > 5 { //5秒还没匹配完成就给玩家匹配机器人
					room_info.RoomStatus = msg.RoomStatus_START
					lack_num := 0
					if room_info.RoomType == msg.RoomType_SHUANG_REN {
						lack_num = 2 - len(room_info.Colors)
					} else {
						lack_num = 4 - len(room_info.Colors)
					}
					addRobotsToRoom(room_info, lack_num)
				}
			}
		}
	}
}

func RemoveColorByColor(temp []msg.RoleType, color msg.RoleType) []msg.RoleType {
	result := make([]msg.RoleType, 0, len(temp))
	for _, item := range temp {
		if item != color {
			result = append(result, item)
		}
	}
	return result
}
func getRoomLackColor(room_info *msg.RoomInfo) msg.RoleType {
	var select_color msg.RoleType
	if room_info.RoomType == msg.RoomType_SHUANG_REN {
		if room_info.Colors[0].MColor == msg.RoleType_BLUE {
			select_color = msg.RoleType_GREEN
		} else {
			select_color = msg.RoleType_BLUE
		}
	} else if room_info.RoomType == msg.RoomType_SIREN_REN {
		var temp []msg.RoleType = make([]msg.RoleType, 0, 4)
		temp = append(temp, msg.RoleType_BLUE)
		temp = append(temp, msg.RoleType_GREEN)
		temp = append(temp, msg.RoleType_RED)
		temp = append(temp, msg.RoleType_YELLOW)

		for i := 0; i < len(room_info.Colors); i++ {
			color_data := room_info.Colors[i]
			temp = RemoveColorByColor(temp, color_data.MColor)
		}
		if len(temp) > 0 {
			select_color = temp[0]
		}
	}
	return select_color
}

func addRobotsToRoom(room_info *msg.RoomInfo, num int) {
	console.Log("addRobotsToRoom:", num)
	for i := 0; i < num; i++ {
		matchInfo := &msg.MatchLudo{
			RoomLevel:      room_info.RoomLevel,
			SelectRoomType: room_info.RoomType,
			SelectColor:    getRoomLackColor(room_info),
		}
		robot_user_id := fmt.Sprintf("robot_%d", i)
		fmt.Printf("matchInfo:%v\n", matchInfo)
		isFullPlayer, err_info := JoinRoom(room_info, matchInfo, robot_user_id)
		if err_info == nil {
			if isFullPlayer {
				start_room := startGame(room_info)
				fmt.Printf("%v:匹配成功开始游戏！", start_room)
				NotifyRoomPlayerMatch(start_room)
			}
		}
	}

}

func getNewRobotPlayer(userId string, room_id int32) (*msg.UserInfo, error) {
	robot_player := &msg.UserInfo{
		UserId: userId,
		MCoin:  getRandomRobotCoin(),
		MHead:  getRandomRobotHead(),
		Name:   getRandomRobotName(),
		RoomId: room_id,
	}
	return robot_player, nil
}
