package logger

import (
	"os"
	"path/filepath"
	"time"

	rotatelogs "github.com/lestrrat/go-file-rotatelogs"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
)

var logger *logrus.Logger
var logWriter *rotatelogs.RotateLogs

func Init(logpath string, loglevel int) error {
	// 创建日志目录
	err := os.MkdirAll(logpath, os.ModePerm)
	if err != nil {
		return err
	}

	logger = logrus.New()
	logname := filepath.Join(logpath, "mtp2_if")

	// 显示行号等信息
	logger.SetReportCaller(true)

	// 设置日志输出
	src, err := os.OpenFile(os.DevNull, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
	if err != nil {
		return err
	}
	logger.SetOutput(src)

	// 设置日志级别
	logger.SetLevel(logrus.Level(loglevel))

	// 设置分割规则
	logWriter, err = rotatelogs.New(
		logname+"_%Y-%m-%d.log",                   // 分割文件名
		rotatelogs.WithMaxAge(7*24*time.Hour),     // 文件最长保存时间
		rotatelogs.WithRotationTime(24*time.Hour), // 日志分割时间
	)

	// 映射日志级别与日志写对象
	writerMap := lfshook.WriterMap{
		logrus.PanicLevel: logWriter,
		logrus.FatalLevel: logWriter,
		logrus.ErrorLevel: logWriter,
		logrus.WarnLevel:  logWriter,
		logrus.InfoLevel:  logWriter,
		logrus.DebugLevel: logWriter,
		logrus.TraceLevel: logWriter,
	}

	// 创建日志文件钩子
	lfHook := lfshook.NewHook(writerMap, &logrus.TextFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	})

	// 添加日志钩子
	logger.AddHook(lfHook)

	return nil
}

func GetLogWriter() *rotatelogs.RotateLogs {
	return logWriter
}

func GetLogger() *logrus.Logger {
	return logger
}
