package internal

import (
	"reflect"
	redismgr "server/db/redis"
	"server/game/ludo"
	"server/msg"

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

func handleMsg(m interface{}, h interface{}) {
	skeleton.RegisterChanRPC(reflect.TypeOf(m), h)
}

// 大厅有进入大厅，离开大厅，加入房间，玩法列表，商城
func init() {
	handleMsg(&msg.EnterHall{}, enterHall)
	handleMsg(&msg.LeaveHall{}, leaveHall)
}

func enterHall(args []interface{}) {
	m := args[0].(*msg.EnterHall)
	a := args[1].(gate.Agent)

	_, err_info := redismgr.GetUserInfoFromRedis(m.UserId)
	if err_info != nil {
		a.WriteMsg(&msg.ResEnterHall{
			Success: false,
			ErrMsg: &msg.MsgError{
				ErrorCode: 101,
				ErrorMsg:  "not find user",
			},
		})
		return
	}
	ud := a.UserData()
	room_id := ud.(*msg.UserInfo).RoomId
	var user_room *msg.RoomInfo = nil
	//如果玩家在某个游戏里，就进行重连
	if room_id != 0 {
		//暂时就一个ludo游戏
		wrapper := ludo.GetBattleRoomById(room_id)
		if wrapper != nil {
			user_room = wrapper.RoomInfo
		} else {
			redismgr.SaveUserInfoToRedis(&msg.UserInfo{
				UserId: ud.(*msg.UserInfo).UserId,
				Name:   ud.(*msg.UserInfo).Name,
				MCoin:  ud.(*msg.UserInfo).MCoin,
				MHead:  ud.(*msg.UserInfo).MHead,
				RoomId: ud.(*msg.UserInfo).RoomId,
			})
		}
		//进行重连逻辑
	}
	a.WriteMsg(&msg.ResEnterHall{
		Success:           true,
		ErrMsg:            nil,
		ReconnectRoomInfo: user_room,
	})
	log.Debug("enterHallHandler, msg: %v, agent: %v", m, a)
}

func leaveHall(args []interface{}) {
	m := args[0].(*msg.LeaveHall)
	a := args[1].(gate.Agent)
	log.Debug("leaveHallHandler, msg: %v, agent: %v", m, a)
}
