package commands

import (
	"crm-api/internal/app"
	"crm-api/pkg/configs"
	"crm-api/pkg/lfshook"
	"crm-api/pkg/utils"
	"fmt"
	"io/ioutil"

	// _ "pms-api-go/api/admin/swagger"  // 20230419 pms 注释

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"github.com/urfave/cli"
	"gopkg.in/natefinch/lumberjack.v2"
)

// CmdWeb cli 命令
var CmdWeb = cli.Command{
	Name:        "web",
	Usage:       "./pbx-api-gin web",
	Description: "Run PBX Web Server",
	Action:      runWeb,
	Flags: []cli.Flag{
		cli.StringFlag{Name: "config, c", Usage: "config file path"},
	},
}

func runWeb(ctx *cli.Context) error {
	if !ctx.IsSet("config") {
		fmt.Print("not set config file path, add -config param")
		return fmt.Errorf("not set config")
	}

	// 解析配置文件
	configs.ConfigPath = ctx.String("config")
	configs.DecodeConfig()
	configs.GetPushConfig()

	if ctx.GlobalIsSet("level") {
		configs.ConfigGlobal.LogLevel = logrus.Level(ctx.GlobalInt("level"))
	} else {
		configs.ConfigGlobal.LogLevel = logrus.InfoLevel
	}

	if ctx.GlobalBool("release") {
		gin.SetMode(gin.ReleaseMode)
	} else {
		gin.SetMode(gin.DebugMode)
	}

	if ctx.GlobalBool("reportCaller") {
		lfshook.NewLogger().Logger.SetReportCaller(true)
	}

	if ctx.GlobalBool("disableConsoleLog") {
		lfshook.NewLogger().Logger.Out = ioutil.Discard
	}

	lfshook.NewLogger().Logger.SetFormatter(&logrus.TextFormatter{
		ForceQuote:      false,
		FullTimestamp:   true,
		TimestampFormat: "01-02 15:04:05",
	})

	pathMap := lfshook.LoggerMap{
		logrus.InfoLevel: &lumberjack.Logger{
			Filename:   configs.ConfigGlobal.LogInfoPath,
			MaxSize:    10, // maxSize M
			MaxBackups: 5,  // keep 5 file
			MaxAge:     7,  //  7 day
		},

		logrus.WarnLevel: &lumberjack.Logger{
			Filename:   configs.ConfigGlobal.LogErrorPath,
			MaxSize:    10, // maxSize M
			MaxBackups: 5,  // keep 5 file
			MaxAge:     7,  //  7 day
		},

		logrus.ErrorLevel: &lumberjack.Logger{
			Filename:   configs.ConfigGlobal.LogErrorPath,
			MaxSize:    10, // maxSize M
			MaxBackups: 5,  // keep 5 file
			MaxAge:     7,  //  7 day
		},
		logrus.FatalLevel: &lumberjack.Logger{
			Filename:   configs.ConfigGlobal.LogErrorPath,
			MaxSize:    10, // maxSize M
			MaxBackups: 5,  // keep 5 file
			MaxAge:     7,  //  7 day
		},
		logrus.PanicLevel: &lumberjack.Logger{
			Filename:   configs.ConfigGlobal.LogErrorPath,
			MaxSize:    10, // maxSize M
			MaxBackups: 5,  // keep 5 file
			MaxAge:     7,  //  7 day
		},
	}

	lfshook.NewLogger().Logger.Hooks.Add(lfshook.NewHook(
		pathMap,
		&logrus.TextFormatter{
			DisableColors:   true,
			ForceQuote:      true,
			TimestampFormat: "01-02 15:04:05",
		},
	))

	app.StartApp()
	utils.Exit()
	return nil
}
