package initutils

import (
	"io"
	"log"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"syscall"
	"time"

	rotatelogs "github.com/lestrrat/go-file-rotatelogs"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

const panicFile = "./log/panic.log"

func InitCoreDump() error {
	if runtime.GOOS == "windows" {
		return nil
	}

	log.Println("init panic file in unix mode")
	file, err := os.OpenFile(panicFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		logrus.Error(err)
		return err
	}

	if err = syscall.Dup2(int(file.Fd()), int(os.Stderr.Fd())); err != nil {
		return err
	}

	return nil
}

func InitLog() {
	if viper.GetBool("log.logrus_json") {
		logrus.SetFormatter(&logrus.JSONFormatter{})
	}

	// log.logrus_level
	switch viper.GetString("log.logrus_level") {
	case "trace":
		logrus.SetLevel(logrus.TraceLevel)
	case "debug":
		logrus.SetLevel(logrus.DebugLevel)
	case "info":
		logrus.SetLevel(logrus.InfoLevel)
	case "warn":
		logrus.SetLevel(logrus.WarnLevel)
	case "error":
		logrus.SetLevel(logrus.ErrorLevel)
	}

	// log.logrus_file
	logrusFile := viper.GetString("log.logrus_file")
	os.MkdirAll(filepath.Dir(logrusFile), os.ModePerm)

	logWriter, _ := rotatelogs.New(
		// 分割后的文件名称
		logrusFile+".%Y%m%d.log",

		// 生成软链，指向最新日志文件
		rotatelogs.WithLinkName(logrusFile),

		// 设置最大保存时间(7天)
		rotatelogs.WithMaxAge(7*24*time.Hour),

		// 设置日志切割时间间隔(1天)
		rotatelogs.WithRotationTime(24*time.Hour),
	)

	if viper.GetBool("log.logrus_console") {
		logrus.SetOutput(io.MultiWriter(logWriter, os.Stdout))
	} else {
		logrus.SetOutput(logWriter)
	}

	// default
	logrus.SetReportCaller(true)
}

func InitConf(configName string) {
	//viper.Set("gormlog", true)
	viper.AddConfigPath("conf")
	viper.AddConfigPath(configName)

	viper.SetConfigName("config")
	viper.SetConfigType("yaml")

	viper.AutomaticEnv()
	viper.SetEnvPrefix("web")
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))

	// 从环境变量总读取
	viper.ReadInConfig()
}
