package main

import (
	"chain33-pai/pkg/app"
	"chain33-pai/pkg/setting"
	"chain33-pai/pkg/util"
	"chain33-pai/routers"
	"chain33-pai/service/pai_service"
	"fmt"
	"github.com/gin-gonic/gin"
	//"log"
	"net"
	"net/http"
	"time"
	clog "github.com/33cn/chain33/common/log"
	log "github.com/33cn/chain33/common/log/log15"
)

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

var tlog = log.New("main", "main.go")
var serial string
// @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() {
	gin.SetMode(setting.ServerSetting.RunMode)
	//区域网广播设备
	go 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.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)
	//}
}


func broadcast()  {
	var pai pai_service.Pai
	send := "hello world"
	if serial != "" {
		send = serial
	} else {
		ok := pai.GetConfig()
		if ok {
			send = pai.Serial
			serial = pai.Serial
		}
	}

	//ip 会变化
	ip,err := util.GetLocalIP()
	if err != nil {
		tlog.Error("broadcast",err)
	}
	// 这里设置发送者的IP地址，自己查看一下自己的IP自行设定
	laddr := net.UDPAddr{
		IP:   ip.IP,
		Port: 8804,
	}

	// 这里设置接收者的IP地址为广播地址
	raddr := net.UDPAddr{
		IP:   net.IPv4(255, 255, 255, 255),
		Port: 8804,
	}
	conn, err := net.DialUDP("udp", &laddr, &raddr)
	if err != nil {
		tlog.Error("broadcast","net error ",err)
		panic(err)
	}

	for {
		_, err = conn.Write([]byte(send))
		if err != nil{
			panic(err)
		}
		tlog.Info("broadcast","udp",send)
		time.Sleep(time.Second*1)
	}
}