package internal

import (
	"reflect"
	redismgr "server/db/redis"
	"server/game"
	"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() {
	print("login:handler")
	handleMsg(&msg.ReqLogin{}, loginHandler)
	handleMsg(&msg.ReqRegister{}, registerHandler)
}

func registerHandler(args []interface{}) {
	// agent := args[1].(gate.Agent)
	m := args[0].(*msg.ReqRegister)
	// 消息的发送者
	a := args[1].(gate.Agent)

	log.Debug(m.Account, m.Password)

	userId, _ := redismgr.GetUserIDFromRedisByAP(m.Account, m.Password)

	if userId != "" {
		a.WriteMsg(&msg.ResRegister{
			Success: false,
			ErrMsg: &msg.MsgError{
				ErrorCode: 101,
				ErrorMsg:  " Account is exist！",
			},
		})
		return
	}

	userId, Success := redismgr.SetUserIDFromRedisByAP(m.Account, m.Password)
	if false == Success {
		a.WriteMsg(&msg.ResRegister{
			Success: false,
			ErrMsg: &msg.MsgError{
				ErrorCode: 102,
				ErrorMsg:  "server registerHandler error",
			},
		})
		return
	}

	redismgr.SaveUserInfoToRedis(&msg.UserInfo{
		UserId: userId,
		MCoin:  0,
		MHead:  m.MHead,
		Name:   m.NikeName,
	})

	a.WriteMsg(&msg.ResRegister{
		Success: true,
		ErrMsg:  nil,
	})

}
func loginHandler(args []interface{}) {
	// agent := args[1].(gate.Agent)
	m := args[0].(*msg.ReqLogin)
	// 消息的发送者
	a := args[1].(gate.Agent)

	log.Debug("loginHandler: %v", args)
	game.ChanRPC.Go("handleAuth", m, a)
}
