package base

import (
	"encoding/json"

	"mongo.games.com/goserver/core/logger"
	"mongo.games.com/goserver/core/netlib"

	"mongo.games.com/game/model"
	"mongo.games.com/game/proto"
	loginproto "mongo.games.com/game/protocol/login"
	playerproto "mongo.games.com/game/protocol/player"
)

func init() {
	// 心跳
	netlib.Register(int(loginproto.GatePacketID_PACKET_SC_PONG), loginproto.SCPong{}, SCPong)
	// 登录
	netlib.Register(int(loginproto.LoginPacketID_PACKET_SC_LOGIN), loginproto.SCLogin{}, SCLogin)
}

func SCPong(s *netlib.Session, packetid int, data interface{}) error {
	return nil
}

func SCLogin(s *netlib.Session, packetid int, data interface{}) error {
	logger.Logger.Trace("SCLogin ", data)

	msg, ok := data.(*loginproto.SCLogin)
	if !ok {
		return nil
	}

	if msg.GetOpRetCode() != loginproto.OpResultCode_OPRC_Sucess {
		accountID := s.GetAttribute(SessionAttributeClientAccountId)
		logger.Logger.Error("登录失败 ", accountID)
		s.Close()
		return nil
	}

	StopSessionLoginTimer(s)
	_, _, _, ip := RandRobotInfo(msg.GetAccId())
	csPlayerData := &playerproto.CSPlayerData{
		AccId: msg.GetAccId(),
	}
	pp := &model.PlayerParams{
		Platform:     1,
		Ip:           ip,
		City:         RandZone(),
		Logininmodel: "app",
	}
	d, err := json.Marshal(pp)
	if err == nil {
		csPlayerData.Params = proto.String(string(d))
	}
	proto.SetDefaults(csPlayerData)
	s.Send(int(playerproto.PlayerPacketID_PACKET_CS_PLAYERDATA), csPlayerData)
	logger.Logger.Info("登录成功 ", msg.GetAccId())
	return nil
}
