//+build go1.9

package main

import (
	"chain33-pai/pkg/app"
	"chain33-pai/pkg/setting"
	"chain33-pai/pkg/util"
	"chain33-pai/routers"
	"fmt"
	"github.com/gin-gonic/gin"

	"chain33-pai/pkg/cmd"
	"chain33-pai/pkg/pai"
	"flag"
	clog "github.com/33cn/chain33/common/log"
	log "github.com/33cn/chain33/common/log/log15"
	"net/http"
	"time"
)

func init() {
	setting.Setup()
	//models.Setup()
	//logging.Setup()
	//gredis.Setup()
	clog.SetFileLog(setting.LogSetting)
	util.Setup()
	app.Setup()
}

var tlog = log.New("main", "main.go")
var (
	versionCmd = flag.Bool("v", false, "version")
	testCmd    = flag.Bool("t", false, "test")
)

// @title Golang Gin API
// @version 1.0
// @description An example of gin
// @termsOfService https://chain33-pai
// @license.name MIT
// @license.url https://chain33-pai/blob/master/LICENSE
func main() {
	flag.Parse()
	if *versionCmd {
		fmt.Println(app.GetVersion())
		return
	}
	if *testCmd {
		fmt.Println("app sys:", cmd.GetLocalArchType(), pai.GetArchType())
		return
	}
	gin.SetMode(setting.ServerSetting.RunMode)
	//区域网广播设备
	go app.Broadcast()
	//节点操作
	go app.BityuanJob(time.NewTicker(time.Second * 30))
	//树莓派内置程序操作
	go app.PaiJob(time.NewTicker(time.Second * 50))
	//go app.ClearLog(time.NewTicker(time.Hour*1))
	go app.RaspberryChan()
	//上传统计树莓派信息
	go app.UploadInfo(time.NewTicker(time.Minute * 10))

	routersInit := routers.InitRouter()
	readTimeout := setting.ServerSetting.ReadTimeout
	writeTimeout := setting.ServerSetting.WriteTimeout
	endPoint := fmt.Sprintf(":%d", setting.ServerSetting.HttpPort)
	maxHeaderBytes := 1 << 20

	server := &http.Server{
		Addr:           endPoint,
		Handler:        routersInit,
		ReadTimeout:    readTimeout,
		WriteTimeout:   writeTimeout,
		MaxHeaderBytes: maxHeaderBytes,
	}

	tlog.Info("[info] start http server listening ", "port", endPoint)
	server.ListenAndServe()
	select {}
	// If you want Graceful Restart, you need a Unix system and download github.com/fvbock/endless
	//endless.DefaultReadTimeOut = readTimeout
	//endless.DefaultWriteTimeOut = writeTimeout
	//endless.DefaultMaxHeaderBytes = maxHeaderBytes
	//server := endless.NewServer(endPoint, routersInit)
	//server.BeforeBegin = func(add string) {
	//	log.Printf("Actual pid is %d", syscall.Getpid())
	//}
	//
	//err := server.ListenAndServe()
	//if err != nil {
	//	log.Printf("Server err: %v", err)
	//}
}
