package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

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

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

}

// @title 智莺生活移动端接口
// @version 1.0
// @description 移动端接口
// @termsOfService 智莺生活后端组
// @contact.name sherlockwhite
// @host localhost:5000
// @securityDefinitions.apikey MasterID
// @in header
// @name MasterID
// @BasePath /
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)
		}
	}()

	/*go func() {
		_ = http.ListenAndServe("0.0.0.0:6060", nil)
	}()*/
	// 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")

}
