package main

import (
	"sync"

	"../log"
	"../mod"
	"../nnet"
	"../nt"
	"../utils"
	"go.uber.org/zap"
)

// Ws server 服务器状态，存储辅助运行信息
type WsServerStatus struct {
	sync.Mutex
	TmpSessions *utils.NvStore	// 临时 session, 未验证登录 guid->ISession
	NewUserFlag *utils.NvStore  // 登录服的验证信息是否需要保存
}

func NewWsServerStatus() *WsServerStatus {
	return &WsServerStatus{
		TmpSessions: utils.NewNvStore(),
		NewUserFlag: utils.NewNvStore(),
	}
}

//func (self *WsServerStatus) RegisterSession(guid uint64, ses nnet.ISession) {
//	self.Lock()
//	if _, ok := self.dups[guid]; ok {
//		log.Warn("dup", zap.Uint64("guid", guid))
//	}
//	self.dups[guid] = ses
//	self.Unlock()
//}
//
//func (self *WsServerStatus) GetRegisterSession(guid uint64) (nnet.ISession, error) {
//	self.Lock()
//	defer self.Unlock()
//
//	if ses, ok := self.dups[guid]; ok {
//		return ses, nil
//	}
//	return nil, utils.ErrKeyNotExists
//}
//
//func (self *WsServerStatus) UnregisterSession(guid uint64) {
//	self.Lock()
//	defer self.Unlock()
//
//	if _, ok := self.dups[guid]; !ok {
//		log.Debug("UnregisterSession", zap.Uint64("guid", guid))
//		return
//	}
//	delete(self.dups, guid)
//}

func (self *WsServerStatus) OnConnected(ses nnet.ISession) (bool, int32) {
	return true, 0
}

func (self *WsServerStatus) OnClosed(ses nnet.ISession, reason int32) {
	guid := ses.Id()
	// no matter what value
	LoginStatus.VerifyTimeout.Remove(guid)

	if nt.DynConf.ValidGuid(guid) {
		log.Debug("session closed", zap.Uint64("guid", guid), zap.Int32("reason", reason))

		arr, err := mod.GetUserAttrs(guid, "balance", "bank")
		var failed int32 = 0
		if nil != err {
			log.Error("get user balance bank", zap.Uint64("guid", guid))
			failed = 1
		}
		balance := utils.If_to_int64(arr[0], 0)
		bank := utils.If_to_int64(arr[1], 0)
		Ev.OnUserLogout(guid, balance, bank, failed, reason)
	}
}

func (self *WsServerStatus) OnMessage(ses nnet.ISession, pkt nnet.IPacket) bool {
	wpkt, ok := pkt.(*KgPacket)
	if !ok {
		log.Error("OnMessage, convert failed.")
		return false
	}
	dispatch(ses, wpkt)
	return true
}

func (self *WsServerStatus) OnHeartbeat(ses nnet.ISession) bool {
	return true
}
