package main

import (
	"fmt"
	"log"
	"net/http"
	"github.com/gin-gonic/gin"

	"chain33-pai/pkg/logging"
	"chain33-pai/pkg/setting"
	"chain33-pai/routers"
	"chain33-pai/models"
	"chain33-pai/pkg/util"
	"net"
	"time"
	"chain33-pai/service/pai_service"
)

func init() {
	setting.Setup()
	models.Setup()
	logging.Setup()
	//gredis.Setup()
	//chain33.Setup()
	util.Setup()
}

// @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()
	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,
	}

	log.Printf("[info] start http server listening %s", 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()  {
	ip,err := util.GetLocalIP()
	if err != nil {
		log.Fatal(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 {
		log.Println(err.Error())
		return
	}
	var pai pai_service.Pai
	send := "hello world"
	ok := pai.GetConfig()
	if ok {
		send = pai.Serial
	}

	for {
		_, err := conn.Write([]byte(send))
		if err != nil{
			fmt.Println(err)
		}
		log.Println(send)
		time.Sleep(time.Second)
	}
}