package main

import (
	"mongo.games.com/game/common"
	login_proto "mongo.games.com/game/protocol/login"
	"mongo.games.com/goserver/core/logger"
	"mongo.games.com/goserver/core/netlib"
)

func SessionLogout(sid int64, drop bool) bool {
	ls := LoginStateMgrSington.GetLoginStateBySid(sid)
	if ls == nil {
		logger.Logger.Trace("SessionLogout ls == nil")
		return false
	}

	ls.state = LoginStateLogout
	p := PlayerMgrSington.GetPlayer(sid)
	if p != nil {
		p.ThirdGameLogout()
		if drop {
			p.DropLine()
		} else {
			p.Logout()
		}
	} else {
		logger.Logger.Trace("SessionLogout p == nil")
	}

	LoginStateMgrSington.Logout(ls)
	return true
}

type CSLogoutPacketFactory struct {
}

type CSLogoutHandler struct {
}

func (this *CSLogoutPacketFactory) CreatePacket() interface{} {
	pack := &login_proto.CSLogout{}
	return pack
}

func (this *CSLogoutHandler) Process(s *netlib.Session, packetid int, data interface{}, sid int64) error {

	logger.Logger.Trace("CSLogoutHandler Process recv ", data)
	SessionLogout(sid, false)
	return nil
}

type SSDisconnectPacketFactory struct {
}

func (this *SSDisconnectPacketFactory) CreatePacket() interface{} {
	pack := &login_proto.SSDisconnect{}
	return pack
}

type SSDisconnectHandler struct {
}

func (this *SSDisconnectHandler) Process(s *netlib.Session, packetid int, data interface{}) error {
	logger.Logger.Trace("SSDisconnectHandler Process recv ", data)
	if ssd, ok := data.(*login_proto.SSDisconnect); ok {
		sid := ssd.GetSessionId()
		if sid != 0 {
			SessionLogout(sid, true)
		}
	}
	return nil
}
func init() {
	// 玩家主动登出
	common.RegisterHandler(int(login_proto.LoginPacketID_PACKET_CS_LOGOUT), &CSLogoutHandler{})
	netlib.RegisterFactory(int(login_proto.LoginPacketID_PACKET_CS_LOGOUT), &CSLogoutPacketFactory{})
	// 玩家掉线
	netlib.RegisterHandler(int(login_proto.GatePacketID_PACKET_SS_DICONNECT), &SSDisconnectHandler{})
	netlib.RegisterFactory(int(login_proto.GatePacketID_PACKET_SS_DICONNECT), &SSDisconnectPacketFactory{})
}
