package gm_rpc

import (
	"gadmin/internal/admin/gm_rpc/gate"
	"gadmin/internal/admin/gm_rpc/grave_master"
	"leafstalk/conf"
	_ "leafstalk/covenant/msg"
	"leafstalk/module"
	"leafstalk/network/cluster"
	"os"

	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

var (
	ExitCh = make(chan struct{}, 1)
)

func Run() {
	logrus.Infoln("gm_rpc service start...")

	//日志分割
	// logrus.SetSplitFile("../logs/gm_rpc.log")

	//加载配置
	cfg1 := InitConf()
	conf := conf.NewConfig(cfg1)

	gate1 := gate.NewModule(PbfRouter, conf)
	module.Register(gate1)

	gmInstance := grave_master.NewModule(MsgRouter, conf)
	module.Register(gmInstance)

	agentServer := gate1.GetHandlerServer()

	//监听端口，且连接网关和世界服务器
	//服务器之间建立链接
	cluster1 := cluster.NewCluster(PbfRouter, agentServer, conf)
	cluster1.SubMsgProcessor = MsgRouter
	//cluster1.Init(conf)
	module.Register(cluster1)

	module.Start()
	<-ExitCh
	//closeSig <- true
	//cluster1.Destroy()
	module.Destroy()
	logrus.Warn("gm rpc closing down...")

}

func InitConf() *viper.Viper {
	conf1 := viper.New()
	conf1.SetEnvPrefix("archive") // allows using env vars in the CHAT_PITAYA_ format

	// conf1.Set("cluster.connaddrs", []conf.ConnAddr{{Tag: 2, Addr: "127.0.0.1:10122"}})
	// conf1.Set("cluster.id", "140")
	// conf1.Set("cluster.servertype", "archive")
	//conf1.Set("cluster.listenaddr", ":10140") //集群监听地址

	conf1.SetConfigFile(os.Getenv("GRAVE_GM"))

	// conf1.AddConfigPath("./conf/")
	// conf1.SetConfigName("gate")
	//conf1.SetConfigType("json")

	// conf1.WriteConfig()
	if err := conf1.ReadInConfig(); err != nil { // 必须 先 读取 `ReadInConfig`
		logrus.Fatal("conf1.ReadInConfig err:", err)
	}

	return conf1
}
