package leaf

import (
	"os"
	"os/signal"
	mergeCluster "server/cluster"
	sconf "server/conf"
	"server/game"
	GoUtil "server/game_util"
	"server/gamedata"
	"server/pkg/github.com/name5566/leaf/cluster"
	"server/pkg/github.com/name5566/leaf/conf"
	"server/pkg/github.com/name5566/leaf/console"
	"server/pkg/github.com/name5566/leaf/log"
	"server/pkg/github.com/name5566/leaf/module"
	"syscall"
	"time"
)

func Run(mods ...module.Module) {
	//logger
	if conf.LogLevel != "" {
		if _, err := os.Stat(conf.LogPath); os.IsNotExist(err) {
			os.Mkdir(conf.LogPath, os.ModePerm)
		}
		zero := GoUtil.ZeroTimestamp()
		now := time.Unix(zero, 0).Local()
		err := log.NewDailyLog(now, log.DEBUG_LEVEL, conf.LogPath, conf.LogFlag)
		if err != nil {
			panic(err)
		}
	}
	log.Release("服务器版本: %s", "1.0.02")
	log.Release("%s 启动, 节点类型: %s, 区服id: %d", sconf.Server.GameName, sconf.Server.ServerType, sconf.Server.ServerID)

	// module
	for i := 0; i < len(mods); i++ {
		module.Register(mods[i])
	}
	module.Init()

	// cluster
	mergeCluster.Init()

	// console
	console.Init()
	defer func() {
		if r := recover(); r != nil {
			log.Debug("Leaf console error: %v", r)
			log.Debug("Leaf closing down\n")
			console.Destroy()
			cluster.Destroy()
			module.Destroy()
			game.Destroy()
			os.Exit(1)
		}
	}()
	// close
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGTERM, syscall.SIGINT)
	for {
		sig := <-c
		if sig == syscall.SIGINT {
			gamedata.Reload()
			continue
		}
		log.Debug("Leaf closing down (signal: %v)\n", sig.String())
		console.Destroy()
		cluster.Destroy()
		module.Destroy()
		game.Destroy()
		os.Exit(1)
	}

}
