package base

import (
	player_proto "mongo.games.com/game/protocol/player"
	"mongo.games.com/goserver/core/logger"
	"mongo.games.com/goserver/core/netlib"
)

/*
 添加到客户端管理器，管理器负责登录
 当连接断开时，从管理器中移除，判断是否需要重连
*/

const (
	GateSessionHandlerName = "handler-gate-session"
)

type GateSessionHandler struct {
	netlib.BasicSessionHandler
}

func (g *GateSessionHandler) GetName() string {
	return GateSessionHandlerName
}

func (g *GateSessionHandler) GetInterestOps() uint {
	return 1<<netlib.InterestOps_Opened |
		1<<netlib.InterestOps_Closed
}

func (g *GateSessionHandler) OnSessionOpened(s *netlib.Session) {
	for accId := range accChan {
		logger.Logger.Infof("连接已建立: sessionID:%v account:%v", s.Id, accId)
		s.SetAttribute(SessionAttributeClientAccountId, accId)
		ClientMgrSingleton.RegisterSession(accId, s)
		delete(accChan, accId)
		return
	}
	logger.Logger.Info("账号已用完，连接断开")
	s.Close()
	return
}

func (g *GateSessionHandler) OnSessionClosed(s *netlib.Session) {
	accIdParam := s.GetAttribute(SessionAttributeClientAccountId)
	isDelAcc := s.GetAttribute(SessionAttributeDelAccount)
	reconnect := false

	logger.Logger.Infof("连接断开 sessionID:%v account:%v accChan:%v", s.Id, accIdParam, len(accChan))
	if accId, ok := accIdParam.(string); ok {
		if isDelAcc == nil {
			accChan[accId] = true
			reconnect = true
		}
		ClientMgrSingleton.UnRegisterSession(accId)
	}

	scPlayerInfoParam := s.GetAttribute(SessionAttributeUser)
	if scPlayerInfo, ok := scPlayerInfoParam.(*player_proto.SCPlayerData); ok {
		PlayerMgrSingleton.DelPlayer(scPlayerInfo.GetData().GetSnId())
	}
	StopSessionPingTimer(s)
	if reconnect {
		logger.Logger.Infof("账号重连 sessionID:%v account:%v", s.Id, accIdParam)
		cfg := Config.Connects
		cfg.Id = s.GetSessionConfig().Id
		cfg.Init()
		WaitConnectSessions = append(WaitConnectSessions, &cfg)
	}
}

func init() {
	netlib.RegisteSessionHandlerCreator(GateSessionHandlerName, func() netlib.SessionHandler {
		return &GateSessionHandler{}
	})
}
