// 逻辑脚本，方法以小写加下划线命名 例：get_money_func
package ludo

import (
	"fmt"
	"server/game"
	"server/msg"
	"server/tools"
	"server/user"
	"time"
)

type RoomInfoWrapper struct {
	*msg.RoomInfo
	TimerManager *tools.TimerManager
	startOptTime time.Time
}

func init() {

}

// 清理解散的房间
func ClearRoomInfoWrapperDisbandRoom() {
	gameConfig.mu.Lock()
	defer gameConfig.mu.Unlock()
	for k := range gameConfig.BattleRoom {
		if gameConfig.BattleRoom[k].RoomStatus == msg.RoomStatus_END {
			delete(gameConfig.BattleRoom, k)
		}
	}
	for k := range gameConfig.RoomMap {
		if gameConfig.RoomMap[k].RoomStatus == msg.RoomStatus_END {
			delete(gameConfig.RoomMap, k)
		}
	}
	fmt.Printf("gameConfig.BattleRoom : %v\n", gameConfig.BattleRoom)
}

func runBattle(room_info *RoomInfoWrapper) {
	gameConfig.mu.Lock()
	defer gameConfig.mu.Unlock()
	// cur_color_key := getCurColorEventKey(room_info)
	// TimerManager.AddEvent(cur_color_key,)
	gameConfig.BattleRoom[room_info.Id] = room_info
	game.Module.AfterFunc(time.Second*time.Duration(3), func() {
		room_info.notify_player_sz()
	})
}

func GetBattleRoomById(id int32) *RoomInfoWrapper {
	gameConfig.mu.Lock()
	defer gameConfig.mu.Unlock()
	room_info, exists := gameConfig.BattleRoom[id]
	if !exists {
		return nil
	}
	return room_info
}

// 根据玩家的骰子数进行相关处理
func (room_info *RoomInfoWrapper) process_sz(msg_body *msg.NotifyPlayerSzNumber) {
	if msg_body.SzNumber == 6 {
		canMoveList := room_info.getRolesBySzNumber(msg_body.Color, msg_body.SzNumber)
		if len(canMoveList) > 0 {
			room_info.notify_player_move(canMoveList)
		} else {
			room_info.setNextPlayerRound()
			room_info.notify_player_sz()
		}
	} else {
		notAtHomeRoles := room_info.getRoleNotAtHomeByColor(msg_body.Color)
		if len(notAtHomeRoles) <= 0 { //全部都在家
			room_info.setNextPlayerRound()
			room_info.notify_player_sz()
		} else if len(notAtHomeRoles) == 4 { //全部都从家里出来了
			canMoveList := room_info.getCanMoveRoles(notAtHomeRoles, msg_body.SzNumber)
			if len(canMoveList) > 0 {
				room_info.notify_player_move(canMoveList)
			} else {
				room_info.setNextPlayerRound()
				room_info.notify_player_sz()
			}
		} else {
			if len(notAtHomeRoles) == 1 { //只有一个选择，那么直接让他走
				//如果一个玩家离终点剩余的步骤不等于筛子数，也将会跳到下个人回合
				if room_info.roleIsCanMove(notAtHomeRoles[0].MId, msg_body.SzNumber) {
					room_info.send_role_move(msg_body.Color, notAtHomeRoles[0].MId)
				} else {
					room_info.setNextPlayerRound()
					room_info.notify_player_sz()
				}
			} else {
				canMoveList := room_info.getCanMoveRoles(notAtHomeRoles, msg_body.SzNumber)
				if len(canMoveList) > 0 {
					room_info.notify_player_move(canMoveList)
				} else {
					room_info.setNextPlayerRound()
					room_info.notify_player_sz()
				}
			}
		}
	}
}

// 根据玩家走的步数进行相关处理
func (room_info *RoomInfoWrapper) process_move(color msg.RoleType, szNumber int32, isAddRound bool, isFinish bool) {
	if room_info.IsOverGame() { //宣布游戏结束
		room_info.notify_settlement()
	} else {
		if szNumber == 6 || isAddRound || isFinish { //加一个回合

		} else { //下个人回合
			room_info.setNextPlayerRound()
		}
		room_info.notify_player_sz()
	}

}

// 通知玩家结算
func (room_info *RoomInfoWrapper) notify_settlement() {
	message := &msg.NotifySettlement{}
	message.FinishColors = room_info.getFinishColors()
	if len(message.FinishColors) == 0 {
		message.FinishColors = room_info.getNotKickColors()
	}
	matchConfig := gameRule.getMatchByLevle(room_info.RoomLevel)
	for _, v := range message.FinishColors {
		if room_info.containsRobot(v.MColor) {

		} else {
			user_id := v.MId
			v.MRewardCoin = matchConfig.rewardNum
			user.AddUserCoin(v.MRewardCoin, user_id)
		}

	}
	room_info.notify_to_all_player(message)
	room_info.dismiss_room()
}

// 通知玩家开始移动角色
func (room_info *RoomInfoWrapper) notify_player_move(list []*msg.RoleData) {
	cur_color := room_info.CurRoundColor
	if len(list) == 1 {
		room_info.send_role_move(cur_color, list[0].MId)
	} else {
		if room_info.containsRobot(cur_color) {
			//如果是机器人，思考一秒然后执行移动角色
			room_info.delay_action_move_robot(1000, cur_color, list)
		}
	}
	room_info.StartCountdownPlayerOpt()
	message := &msg.NotifyPlayerOpt{
		Color:        room_info.CurRoundColor,
		Opt:          msg.OptType_SELECT_ROLE,
		CanMoveRoles: list,
		OptTime:      room_info.Get_cur_color_opt_time(),
	}
	room_info.notify_to_all_player(message)
	room_info.setCurColorOpt(message)

}

// 通知玩家状态
func (room_info *RoomInfoWrapper) notify_player_status(color msg.RoleType, status msg.PlayerStatus, colors []*msg.ColorData) {
	message := &msg.NotifyPlayerStatus{
		Color:  color,
		Status: status,
		Colors: colors,
	}
	room_info.notify_to_all_player(message)
}

// 获取当前回合玩家的操作时间
func (room_info *RoomInfoWrapper) Get_cur_color_opt_time() int32 {
	end := time.Now()
	// 计算整数秒（直接截断小数部分）
	seconds := int(end.Sub(room_info.startOptTime).Seconds())
	opt_time := gameRule.OPT_TIME - int32(seconds)
	fmt.Printf("room_info.OptTime:%d,%d\n", seconds, opt_time)
	return opt_time
}

// 通知玩家要骰子
func (room_info *RoomInfoWrapper) notify_player_sz() {
	cur_color := room_info.CurRoundColor
	room_info.StartCountdownPlayerOpt()
	message := &msg.NotifyPlayerOpt{
		Color:   cur_color,
		Opt:     msg.OptType_ZHI_SHAI_ZI,
		OptTime: room_info.Get_cur_color_opt_time(),
	}
	room_info.notify_to_all_player(message)
	room_info.setCurColorOpt(message)

	if room_info.containsRobot(cur_color) {
		fmt.Printf("robot_sz_time:%v:\n", time.Now())
		game.Module.Skeleton.AfterFunc(time.Duration(2000)*time.Millisecond, func() {
			fmt.Printf("robot_sz_time:%v:\n", time.Now())
			room_info.send_sz(cur_color)
		})
	} else {

	}
}

// 托管操作一次
func (room_info *RoomInfoWrapper) tuo_guan_opt() {
	curColorOpt := room_info.CurColorOptData.Opt
	curColor := room_info.CurRoundColor
	if curColorOpt == msg.OptType_SELECT_ROLE {
		role_id := room_info.CurColorOptData.CanMoveRoles[0].MId
		room_info.send_role_move(curColor, role_id)
	} else if curColorOpt == msg.OptType_ZHI_SHAI_ZI {
		room_info.send_sz(curColor)
	}
	message := &msg.NotifyPlayerStatus{
		Color:        curColor,
		TimeOutColor: room_info.getColorDataByColor(curColor),
		Status:       msg.PlayerStatus_COLOR_TIME_OUT,
	}
	room_info.notify_to_all_player(message)
}

// 超过10秒玩家没有操作，将他的timeout 累计加1，然后给他托管一次
func (room_info *RoomInfoWrapper) time_out_tuo_guan() {
	cur_color := room_info.CurRoundColor
	color_data := room_info.getColorDataByColor(cur_color)
	color_data.TimeOutNum = color_data.TimeOutNum + 1
	if color_data.TimeOutNum > 5 { //如果玩家累计5次托管行为，将玩家踢出房间
		room_info.kickColor(cur_color)
		if room_info.IsOverGame() { //宣布游戏结束
			room_info.notify_settlement()
		} else {
			room_info.kick_color_of_room(cur_color)
		}
	} else {
		room_info.tuo_guan_opt()
	}
}

// 开始计时玩家操作
func (room_info *RoomInfoWrapper) StartCountdownPlayerOpt() {
	room_info.startOptTime = time.Now()
	room_info.OptTime = gameRule.OPT_TIME
	room_info.TimerManager.AddEvent(room_info.GetRoomTimeOutKey(), time.Duration(gameRule.OPT_TIME)*time.Second, room_info.time_out_tuo_guan)
}

// 取消玩家计时
func (room_info *RoomInfoWrapper) CancelCountdownPlayerOpt() {
	room_info.TimerManager.RemoveEvent(room_info.GetRoomTimeOutKey())
}

// 房间里通知所有玩家
func (room_info *RoomInfoWrapper) notify_to_all_player(message interface{}) {
	for i := range room_info.Colors {
		color_data := room_info.Colors[i]
		user_id := color_data.MId
		if room_info.containsRobot(color_data.MColor) {

		} else {
			user_agent := getAgentByUserId(user_id)
			if user_agent != nil && !color_data.IsKick {
				user_agent.WriteMsg(message)
			}
		}

	}
}

// 房间里通知所有玩家包括被踢出的玩家
func (room_info *RoomInfoWrapper) notify_all_player(message interface{}) {
	for i := range room_info.Colors {
		color_data := room_info.Colors[i]
		user_id := color_data.MId
		if room_info.containsRobot(color_data.MColor) {

		} else {
			user_agent := getAgentByUserId(user_id)
			if user_agent != nil {
				user_agent.WriteMsg(message)
			}
		}

	}
}

// 给前端展示一段时间后，再操作
func (room_info *RoomInfoWrapper) delayActionNextRound(td int32, color msg.RoleType, szNumber int32, isAddRound bool, isFinish bool) {
	dtn := time.Duration(td) * time.Millisecond
	game.Module.Skeleton.AfterFunc(dtn, func() {
		room_info.process_move(color, szNumber, isAddRound, isFinish)
	})
}

// 给前端展示一段时间后，再操作
func (room_info *RoomInfoWrapper) delay_action_sz(td int, msg_body *msg.NotifyPlayerSzNumber) {
	dtn := time.Duration(td) * time.Millisecond
	game.Module.Skeleton.AfterFunc(dtn, func() {
		room_info.process_sz(msg_body)
	})
}

// 延迟后，移动机器人
func (room_info *RoomInfoWrapper) delay_action_move_robot(td int, color msg.RoleType, list []*msg.RoleData) {
	dtn := time.Duration(td) * time.Millisecond
	game.Module.Skeleton.AfterFunc(dtn, func() {
		role := getRandomItem(list)
		room_info.send_role_move(color, role.MId)
	})
}

// 更新房间信息发送给玩家
func (room_info *RoomInfoWrapper) notify_update_room_info() {
	room_info.notify_to_all_player(&msg.NotifyUpdateRoomInfo{
		RoomInfo: room_info.RoomInfo,
	})
}

// 将玩家从房间踢出
func (room_info *RoomInfoWrapper) kick_color_of_room(color msg.RoleType) {
	message := &msg.NotifyPlayerStatus{
		Color:  color,
		Status: msg.PlayerStatus_COLOR_KICK,
		Colors: room_info.getKickColors(),
	}
	room_info.notify_all_player(message)
}

// 解散房间
func (room_info *RoomInfoWrapper) dismiss_room() {
	room_info.CancelCountdownPlayerOpt()
	//将战绩给玩家存档

	//移除房间
	room_info.RoomStatus = msg.RoomStatus_END
	for i := 0; i < len(room_info.Colors); i++ {
		color_data := room_info.Colors[i]
		user_agent := getAgentByUserId(color_data.MId)
		if user_agent != nil {
			ud := user_agent.UserData().(*msg.UserInfo)
			ud.RoomId = 0
			user_agent.SetUserData(ud)
		}
	}
	ClearRoomInfoWrapperDisbandRoom()
}
