package main

import (
	"os"
	"time"

	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
	prefixed "github.com/x-cray/logrus-prefixed-formatter"
)

type TagHook struct {
	Tag string
}

func NewTagHook(tag string) logrus.Hook {
	hook := TagHook{
		Tag: tag,
	}
	return &hook
}

func (hook *TagHook) Fire(entry *logrus.Entry) error {
	entry.Data["tag"] = hook.Tag
	return nil
}

func (hook *TagHook) Levels() []logrus.Level {
	return logrus.AllLevels
}

var stdFormatter *prefixed.TextFormatter  // 命令行输出格式
var fileFormatter *prefixed.TextFormatter // 文件输出格式

func init() {
	stdFormatter = &prefixed.TextFormatter{
		FullTimestamp:   true,
		TimestampFormat: "2006-01-02.15:04:05",
		ForceFormatting: true,
		ForceColors:     false,
		DisableColors:   true,
	}
	fileFormatter = &prefixed.TextFormatter{
		FullTimestamp:   true,
		TimestampFormat: "2006-01-02.15:04:05",
		ForceFormatting: true,
		ForceColors:     false,
		DisableColors:   true,
	}
}

func NewLogger(logfile string) *logrus.Logger {
	logger := logrus.New()
	configureLogger(logger, logfile, logrus.InfoLevel)

	return logger
}

func configureLogger(logger *logrus.Logger, logfile string, level logrus.Level) {
	logger.SetFormatter(stdFormatter)
	logger.SetLevel(logrus.Level(level))
	writer, _ := rotatelogs.New(
		logfile+".%Y%m%d",
		rotatelogs.WithLinkName(logfile),
		rotatelogs.WithMaxAge(time.Duration(7*24)*time.Hour),
		rotatelogs.WithRotationTime(time.Duration(24)*time.Hour),
	)

	lfHook := lfshook.NewHook(lfshook.WriterMap{
		logrus.InfoLevel:  writer,
		logrus.DebugLevel: writer,
		logrus.ErrorLevel: writer,
	}, fileFormatter)

	logger.SetOutput(os.Stdout)
	logger.AddHook(lfHook)
}
