package main

import (
	"World/clubmgr"
	"World/conf"
	"World/game"
	"World/logic"
	nt "World/network"
	"World/resume"
	"World/utils"
	"common/logger"
	"flag"
	"log"
	"math/rand"
	"os"
	"runtime/pprof"
	"time"
	"World/mail"
)

func InitLogger(file string, lvl int) {
	logger.New(file, lvl, logger.Rotate{Size: logger.GB, Expired: time.Hour * 24 * 7, Interval: time.Hour * 24})
}

func main() {

	defer utils.PrintPanicStack()

	filename := flag.String("conf_path", "./conf/world.xml", "config file path")
	//filename := flag.String("conf_path", "E:/coin_server/src/World/conf/world.xml", "config file path")
	logpath := flag.String("logpath", "./log", "log file path")
	//logpath := flag.String("logpath", "E:/coin_server/src/World/log", "log file path")
	cpuprofile := flag.String("cpuprofile", "", "write cpu profile to file")
	secs := flag.Int("exitsecs", 0, "how many secs to exit, defaut 0 to never exit")
	lvl := flag.Int("lvl", 6, "log level default -debug")
	flag.Parse()
	InitLogger(*logpath+"/world.log", *lvl)
	logger.Info("config file path:%v", *filename)

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			logger.Info("open cpu profile error %v:", err)
		} else {
			pprof.StartCPUProfile(f)
			defer pprof.StopCPUProfile()
		}
	}
	var ch chan int = make(chan int)
	go waitFor(ch, *secs)

	//init rand seed
	rand.Seed(time.Now().UTC().UnixNano())

	//init config
	err := conf.LoadConf(*filename)
	if err != nil {
		logger.Info("error load conf fail %v:", err)
		return
	}

	logger.Info("load config file %v: success!", *filename)

	err = resume.Init()
	if err != nil {
		logger.Notic("init redis failed:%v err", err)
		return
	}

	game.Init()

	log.Println("after game Init()")
	logger.Info("after game Init()")

	//init
	clubmgr.Init()

	log.Println("after clubmgr.Init()")
	logger.Info("after clubmgr.Init()")

	go nt.StartSocketServer()

	log.Println("after nt.StartSocketServer()")
	logger.Info("after nt.StartSocketServer()")

	// gpc逻辑
	go clubmgr.DoGRPC()
	log.Println("after clubmgr.DoGRPC()")
	logger.Info("after clubmgr.DoGRPC()")

	go logic.StartHttpServe()

	err = mail.InitMail()
	if err != nil {
		logger.Notic("mail.InitMail failed err:%v",err)
		return
	}

	select {
	case _ = <-ch:
		logger.Info("---I'm done----")
		break
	}
}

func waitFor(ch chan int, secs int) {
	if secs <= 0 {
		return
	}
	time.Sleep(time.Duration(secs) * time.Second)

	logger.Info("-------------ready to exit--------------------")
	ch <- 1
}
