package main

import (
	"code.fnuoos.com/zhimeng/model.git/src"
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"applet/app/cfg"
	"applet/app/router"
	"applet/app/utils"
)

// 系统初始化
func init() {
	cfg.InitCfg()   //配置初始化
	cfg.InitLog()   //日志初始化
	cfg.InitCache() //缓存初始化
	if cfg.Debug {  //判断是否是debug
		if err := db.InitDB(cfg.DB); err != nil { //主数据库初始化
			panic(err)
		}
		channel := make(chan int, 0) //开辟管道,缓冲为
		go db.InitDBs(channel)
		<-channel
	}
	fmt.Println("init success")

}

// @title 广告联盟-总站长平台
// @version 1.0
// @description 总站长后台接口
// @termsOfService http://swagger.io/terms/

// @contact.name dengbiao
// @contact.url http://www.swagger.io/support
// @contact.email 1239118001@qq.com

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// @host localhost:1001 or advertisement.dengbiao.top
// @securityDefinitions.apikey MasterID
// @in header
// @name MasterID
// @BasePath /api
func main() {
	// 启动获取所有品牌
	//go taoke.GetAllBrand()
	r := router.Init() //创建路由
	// arkid.Init()
	srv := &http.Server{ //设置http服务参数
		Addr:    cfg.SrvAddr, //指定ip和端口
		Handler: r,           //指定路由
	}
	// 读取默认站长的推广位 并写进redis
	// master, err := db.UserProfileFindByID(,"1")

	// if err != nil {
	// 	panic(err)
	// }
	if cfg.CurlDebug {
		utils.CurlDebug = true
	}
	//
	// if has := cache.SetJson(svc.SysCfgGet(nil, "app_name")+"_default_pid_user", master, 0); has != true {
	// 	panic(errors.New("设置默认pid缓存失败"))
	// }
	// Initializing the server in a goroutine so that it won't block the graceful shutdown handling below
	go func() { //协程启动监听http服务
		fmt.Println("Listening and serving HTTP on " + cfg.SrvAddr)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()
	// graceful shutdown
	//退出go守护进程
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutting down server...")
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server forced to shutdown:", err)
	}
	log.Println("Server exiting")

}