package internal

import (
	"reflect"
	redismgr "server/db/redis"
	"server/hall/shop"

	agentmanager "server/game/agentManager"
	"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)
	HandleMsg(&msg.BuyShopItem{}, shop.OnBuy)
}

func enterHall(args []interface{}) {
	m := args[0].(*msg.EnterHall)
	a := args[1].(gate.Agent)
	agentmanager.AgentConnStatusAuthed(a)
	user_info, 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
	}
	//如果玩家其他玩家登陆了账号
	if isLogin, otherAgent := agentmanager.IsAuthedUsers(m.UserId, a); isLogin && otherAgent != nil {
		otherAgent.WriteMsg(&msg.BeKickLogin{
			ErrMsg: &msg.MsgError{
				//你的账号被其他人登陆
				ErrorMsg:  "Your account has been logged in by someone else",
				ErrorCode: 101,
			},
		})
		agentmanager.KickAgent(m.UserId)
	}
	agentmanager.AddAuthedUsers(m.UserId, a)
	a.SetUserData(&msg.UserInfo{
		UserId: user_info.UserId,
		MHead:  user_info.MHead,
		MCoin:  user_info.MCoin,
		Name:   user_info.Name,
		RoomId: user_info.RoomId,
	})
	room_id := user_info.RoomId
	var user_room *msg.RoomInfo = nil
	//如果玩家在某个游戏里，就进行重连
	if room_id != 0 {
		//暂时就一个ludo游戏
		wrapper := ludo.GetBattleRoomById(room_id)
		if wrapper != nil {
			wrapper.OptTime = wrapper.Get_cur_color_opt_time()
			user_room = wrapper.RoomInfo
		} else {
			redismgr.SaveUserInfoToRedis(&msg.UserInfo{
				UserId: user_info.UserId,
				Name:   user_info.Name,
				MCoin:  user_info.MCoin,
				MHead:  user_info.MHead,
				RoomId: user_info.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)
}
