package main

import (
	"../log"
	"../nt"
	"./executor"
	"context"
	"flag"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var (
	TaskPool *executor.TaskPool
	FileConf string
	ChQuit       chan struct{} = make(chan struct{})
	Ev                         = new(TaskEvent)
)

const (
	TASK_SUCCESS = 0
	TASK_FAILED = 1
)
func main() {

	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
	}

	init_by_conf(FileConf)

	register_DBDZ()
	register_FG()
	register_IG()
	register_VG()
	register_ZZYL()
	register_CQ9()

	init_pool()

	gin.SetMode(nt.InstConf.Mode)

	r := MakeRouter()

	addr := fmt.Sprintf("%s:%d", nt.InstConf.Host, nt.InstConf.Port)
	server := &http.Server{
		Addr:    addr,
		Handler: r,
	}
	go func() {
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			fmt.Println("listen error:", err)
		}
	}()

	chSig := make(chan os.Signal)
	signal.Notify(chSig, syscall.SIGINT, syscall.SIGTERM)

	fmt.Println("Signal:", <-chSig) // will be blocked here

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := server.Shutdown(ctx); err != nil {
		fmt.Println("Server shutdown error:", err)
	}
	select {
	case <-ctx.Done():
		fmt.Println("Timeout and quit")
	}
	//
	close(ChQuit)

	TaskPool.Stop()

	fmt.Println("Server Exited.")
}

func err_log(err error,content interface{}){
	log.Debug("Executor_JBD_QP",zap.Error(err),zap.Any("data",content))
}