package log

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

var logLevels = map[logrus.Level]string{
	logrus.DebugLevel: "debug",
	logrus.InfoLevel:  "info",
	logrus.WarnLevel:  "warn",
	logrus.ErrorLevel: "error",
}

func NewRotateHook(l logrus.Level, path string, day uint, pass bool) logrus.Hook {
	var writerMap = lfshook.WriterMap{}
	if path == "" {
		path = "."
	}

	name := path + "/" + logLevels[l]
	writer, err := rotatelogs.New(
		name+"_%Y%m%d.log",
		rotatelogs.WithLinkName(name+".log"),
		rotatelogs.WithRotationTime(time.Hour*24),
		rotatelogs.WithRotationCount(day),
	)
	if err != nil {
		logrus.Errorf("config local file system for logger error: %v", err)
	}

	for level := logrus.ErrorLevel; level <= logrus.DebugLevel; level++ {
		if level != l && (level > l || !pass) {
			continue
		}

		writerMap[level] = writer
	}

	rotateHook := lfshook.NewHook(writerMap, &LineFormatter{
		Skip: 13,
	})

	return rotateHook
}
