package cmd

import (
	"fmt"
	"git.wanbits.cc/sin/flytalk/config"
	"git.wanbits.cc/sin/flytalk/controller"
	"git.wanbits.cc/sin/flytalk/g"
	"git.wanbits.cc/sin/flytalk/models"
	"git.wanbits.cc/sin/flytalk/router"
	"git.wanbits.cc/sin/flytalk/tools"
	"git.wanbits.cc/sin/flytalk/user/provider/twong"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
	"log"
	"os"
	"os/exec"
	"path/filepath"
)

var (
	Addr    string
	Confile string
	Daemon  bool
)

var serverCmd = &cobra.Command{
	Use:     "serve",
	Short:   "start serving",
	Example: "flytalk serve -c config",
	Run: func(cmd *cobra.Command, args []string) {
		run()
	},
}

func run() {
	// load config
	_, err := config.LoadConf(Confile)
	if err != nil {
		panic(fmt.Sprintf("load config file failed:%v", Confile))
	}
	fmt.Println("============Config============")
	fmt.Printf("Basic:%+v\n", config.C.Basic)
	fmt.Printf("Database:%+v\n", config.C.Database)
	fmt.Printf("Imap:%+v\n", config.C.Imap)
	fmt.Printf("Twong:%+v\n", config.C.Twong)
	if config.C.Basic.Daemon {
		if os.Getppid() != 1 {
			// 将命令行参数中执行文件路径转换成可用路径
			filePath, _ := filepath.Abs(os.Args[0])
			cmd := exec.Command(filePath, os.Args[1:]...)
			// 将其他命令传入生成出的进程
			cmd.Stdin = os.Stdin // 给新进程设置文件描述符，可以重定向到文件中
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			cmd.Start() // 开始执行新进程，不等待新进程退出
			os.Exit(0)
		}
	}

	// load i18n
	l := g.NewLang(config.C.Basic.LangDir)
	g.SetDefaultLang(l)

	// connect to db
	models.InitDb()
	twong.InitDb()
	controller.Init()

	log.Println("start server at " + config.C.Basic.Addr)

	gin.SetMode(gin.ReleaseMode)

	engine := gin.Default()
	engine.Use(cors.Default())
	//htmlGlobDir := filepath.Join(config.C.Basic.ResDir, "html/*")
	engine.LoadHTMLGlob("static/html/*")
	engine.Static("/static", "./static")

	//记录日志
	engine.Use(tools.LoggerToFile())

	router.InitViewRouter(engine)
	router.InitApiRouter(engine)
	//文档服务
	//docs.SwaggerInfo.Title = "接口文档"
	//docs.SwaggerInfo.Description = "flytalk 客服系统 , 测试账户:kefu2 测试密码:123 类型:kefu"
	//docs.SwaggerInfo.Version = "0.0.7"
	////docs.SwaggerInfo.Host = "127.0.0.1:"+port
	//docs.SwaggerInfo.Host = "flytalk.sopans.com"
	//docs.SwaggerInfo.BasePath = "/"
	//docs.SwaggerInfo.Schemes = []string{"https"}
	//engine.GET("/docs/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	err = engine.Run(config.C.Basic.Addr)
	fmt.Println("quit:", err)
}
