package gate

import (
	"errors"
	"github.com/golang/protobuf/proto"
	"leafstalk/conf"
	"leafstalk/module"
	"leafstalk/module/handler"
	"leafstalk/router/protobuf"
)

type Module struct {
	*module.Skeleton
	config    *conf.Config
	Processor *protobuf.Processor
}

// var dbRpc *handler.Server
var skeleton *module.Skeleton
var errServerNotFound = errors.New("server not found...")

// func SetDbRpc(rpc *handler.Server) {
// 	dbRpc = rpc
// }

// NewModule 构造
func NewModule(processor *protobuf.Processor, config *conf.Config) *Module {
	mod := new(Module)
	mod.config = config

	//构造一个数据处理模块
	mod.Skeleton = module.NewSkeleton(config)
	mod.Processor = processor
	skeleton = mod.Skeleton
	return mod
}

// GetHandlerServer 获取
func (m *Module) GetHandlerServer() *handler.Server {
	return m.HandlerServer
}

// OnInit 1
func (m *Module) OnInit() {
	//m.Skeleton.RegisterChanRPC("NewClusterAgent", m.rpcNewClusterAgent)
	//m.Skeleton.RegisterChanRPC("CloseClusterAgent", rpcCloseClusterAgent)
	//
	//m.handleMsg(&pbfmsg.ServerLogin{}, m.handleServerLogin)
	//m.handleMsg(&pbfmsg.ResponseServerLogin{}, handleResponseServerLogin)
	//
	////设置定时器
	//cronExpr, err := timer.NewCronExpr("*/1 * * * *")
	//if err != nil {
	//	panic("定时器设置失败!")
	//}
	//m.Skeleton.CronFunc(cronExpr, m.onTimer)

}

func (m *Module) onTimer() {
	//服务器没认证，则定时进行认证
	//servers.AuthAllServer(m.config)

	// a := []interface{}{join}
	// handleCreateRoom(a)
}

// handleMsg 消息结构体注册处理函数
func (m *Module) handleMsg(msg proto.Message, h interface{}) {
	/*//设置处理函数
	m.RegisterChanRPC(reflect.TypeOf(msg), h)

	//消息路由目标是本模块
	m.Processor.SetRouter(msg, m.HandlerServer)*/
}

func (m *Module) handleRpcMsg(msg interface{}, h interface{}) error {
	/*msgType := reflect.TypeOf(msg)
	if msgType == nil || msgType.Kind() != reflect.Ptr {
		return errors.New("json message pointer required")
	}
	msgID := msgType.Elem().Name()
	m.Skeleton.RegisterChanRPC(msgID, h)*/
	return nil
}

// OnDestroy 1
func (m *Module) OnDestroy() {
	//GetLogicApp().Destory()
}

var (
	sendToWorldRetryCount = 0
	cleanRetryCount       = func() {
		sendToWorldRetryCount = 0
	}
)

func SendToWorld(id int64, msg interface{}) (err error) {
	return errors.New("SendToWorld..")
	//if sendToWorldRetryCount > 0 {
	//	defer cleanRetryCount()
	//}
	//
	//server := servers.GetWorldServer()
	//if server == nil {
	//	// 服务重试
	//	if sendToWorldRetryCount < 5 {
	//		sendToWorldRetryCount++
	//		logrus.Info("sendToWorldRetry:", sendToWorldRetryCount)
	//		time.Sleep(time.Second * 1)
	//		return SendToWorld(id, msg)
	//	}
	//	return errServerNotFound
	//}
	//
	//data, err := json.Marshal(msg)
	//if err != nil {
	//	logrus.Errorln("SendToWorld json.Marshal err:", err)
	//}
	//
	//logrus.WithField("from", "SendToWorld").Infoln(id, string(data))
	//if err = server.Agent.WriteRouteMsg2(msg, id); err != nil {
	//	logrus.Errorln(err)
	//}
	//return
}
