package main

import (
	"../nt"
	"../prof"
	"flag"
	"fmt"
	"os"
	"os/signal"
	"runtime"
	"syscall"
	"time"
)

var (
	FileConf string                              // 本实例使用的配置文件名称 通过命令行参数传入
	ChQuit   chan struct{} = make(chan struct{}) // 退出时关闭
	ChReconn chan<- int                          // 重连 Login 服务的 channel，发送任意数据到本通道将触发重连
	Ev       *LobbyEvent   = new(LobbyEvent)     // 事件对象
	Online   int           = 1                   // 服务器在线
)

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	var ver bool = false
	flag.StringVar(&FileConf, "c", "conf.json", "config file")
	flag.BoolVar(&ver, "v", false, "print version")
	flag.Parse()

	if ver {
		fmt.Println(VERSION)
		return
	}

	nt.BootTime = time.Now()

	init_by_conf()

	//
	profile := prof.NewProf(nt.InstConf.ProfAddr, true)

	nt.PrintInstInfo(nt.Mac)

	listenForClients()

	// 重连线程
	ChReconn = start_reconn_thread(5 * time.Second)
	// 调试状态
	start_monitor()

	chSig := make(chan os.Signal)
	signal.Notify(chSig, syscall.SIGINT, syscall.SIGTERM)
	fmt.Println("Signal:", <-chSig)

	//
	profile.Stop()

	quit()
}

func quit() {
	ClearLogicFlags()
	ClearAgentFlags()
	close(ChQuit)
	Server.Stop()
	nt.Zk.Close()
	nt.Rdb.Close()
	fmt.Println("quit")
}

func start_monitor() {
	go func() {
		tm := time.NewTicker(time.Second)
		for {
			select {
			case <-ChQuit:
				fmt.Println("monitor quit.")
				return
			case <-tm.C:
				now := time.Now()
				if now.Second() == 0 {
					on_every_1min()

					if now.Minute() == 0 {
						on_every_1hour()

						if now.Hour() == 0 {
							on_daily_00_00()

							if now.Weekday() == time.Monday {
								on_weekly_00_00()
							}
							if now.Day() == 1 {
								on_monthly_00_00()
							}
							if now.YearDay() == 1 {
								on_yearly_00_00()
							}
						}
					}
					if now.Minute() % 3 == 0 {
						on_every_3min()
					}
				}
			}
		}
	}()
}


func print_debug_message() {
	fmt.Println("session num:", Server.GetSessionNum())
	fmt.Println("waits num", LoginStatus.VerifyTimeout.Num())
	fmt.Println("session Save num:", ServerStatus.NewUserFlag.Num())
	fmt.Println("session pending", ServerStatus.TmpSessions.Num())
}