package ludo

import (
	"fmt"
	"server/msg"
	"server/user"

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

func RecvMatchLudo(args []interface{}) {
	log.Error("RecvMatchLudo!")
	m := args[0].(*msg.MatchLudo)
	a := args[1].(gate.Agent)
	ud := a.UserData()
	user_id := ud.(*msg.UserInfo).UserId
	log.Error("user_id:=%s , start match!", user_id)
	//判断玩家是否有足够金币
	coin := ud.(*msg.UserInfo).MCoin
	matchConfig := gameRule.getMatchByLevle(m.RoomLevel)
	fmt.Printf("coin = %d \n", coin)
	fmt.Printf("RoomLevel = %d \n", m.RoomLevel)
	fmt.Printf("matchConfig.enterNum = %v \n", matchConfig.enterNum)
	if coin >= matchConfig.enterNum {
		user.DecreaseUserCoin(matchConfig.enterNum, user_id)
		go matchRoom(m, user_id, a)
	} else {
		sendMatchErrorMsg(a, 101, "Not enough gold coins")
	}
}

//根据玩家要匹配的对局，给玩家寻找和的房间

func matchRoom(matchInfo *msg.MatchLudo, userId string, user_agent gate.Agent) {
	fmt.Printf("matchRoom\n")
	roomList := GetRoomsByLevel(matchInfo, msg.RoomStatus_AWAIT)
	fmt.Printf("matchRoom123\n")
	if len(roomList) == 0 {
		// Create new room if none available
		fmt.Printf("没找到房间匹配一个！\n")
		_, err := CreateRoom(matchInfo, userId)
		if err != nil {
			fmt.Printf("%s\n", err.Error())
			sendMatchErrorMsg(user_agent, 101, "not find player")
		}
	} else {
		log.Error("匹配到%d个房间", len(roomList))
		// 如果房间具备开始的条件
		isFullPlayer, err_info := JoinRoom(roomList[0], matchInfo, userId)
		if err_info == nil {
			if isFullPlayer {
				start_room := startGame(roomList[0])
				fmt.Printf("%v:匹配成功开始游戏！", start_room)
				NotifyRoomPlayerMatch(start_room)
			}
		} else {
			sendMatchErrorMsg(user_agent, 101, "not find player")
		}
	}
}

// 通知房间玩家匹配成功
func NotifyRoomPlayerMatch(room_info *RoomInfoWrapper) {
	for i := range room_info.Colors {
		user_id := room_info.Colors[i].MId
		user_agent := getAgentByUserId(user_id)
		if user_agent != nil {
			user_agent.WriteMsg(&msg.ResMatchLudo{
				Room:    room_info.RoomInfo,
				Success: true,
				ErrMsg:  nil,
			})
		}
	}
}

func sendMatchErrorMsg(user_agent gate.Agent, error_code int32, msg_str string) {
	if user_agent != nil {
		user_agent.WriteMsg(&msg.ResMatchLudo{
			Success: false,
			ErrMsg: &msg.MsgError{
				ErrorCode: error_code,
				ErrorMsg:  msg_str,
			},
		})
	}
}
