package config

import (
	"io"
	"os"
	"path/filepath"
	"runtime"
	"strconv"
	"sync"

	"github.com/sirupsen/logrus"
	"gopkg.in/natefinch/lumberjack.v2"
)

// 设置日志记录控制
func BuildLogger() {
	initLogger()
	initAccessLogger()
}

func initLogger() {
	level := os.Getenv("LOG_LEVEL")
	logLevel := 5
	switch level {
	case "panic":
		logLevel = 0
	case "fatal":
		logLevel = 1
	case "error":
		logLevel = 2
	case "warn":
		logLevel = 3
	case "info":
		logLevel = 4
	case "debug":
		logLevel = 5
	case "trace":
		logLevel = 6
	}
	logrus.SetLevel(logrus.Level(logLevel))

	formatter := &logrus.TextFormatter{
		ForceColors:     true,
		FullTimestamp:   true,
		DisableQuote:    true,
		TimestampFormat: "2006-01-02 15:04:05",
		CallerPrettyfier: func(frame *runtime.Frame) (function string, file string) {
			return "", " " + filepath.Base(frame.File) + ":" + strconv.Itoa(frame.Line)
		},
	}
	logrus.SetFormatter(formatter)

	logger := &lumberjack.Logger{
		LocalTime:  true,
		Filename:   os.Getenv("LOG_PATH"),
		MaxSize:    50,   // 一个文件最大为50M
		MaxBackups: 10,   // 最多同时保存10份文件
		MaxAge:     15,   // 一个文件最多同时存在15天
		Compress:   true, // 压缩
	}
	writers := []io.Writer{
		logger,
		os.Stdout,
	}
	fileAndStdoutWriter := io.MultiWriter(writers...)
	logrus.SetOutput(fileAndStdoutWriter)
}

var (
	AccessLog     *logrus.Logger
	accessLogOnce = sync.Once{}
)

func initAccessLogger() {
	accessLogOnce.Do(func() {
		AccessLog = logrus.New()
		AccessLog.SetFormatter(&logrus.TextFormatter{})

		logger := &lumberjack.Logger{
			LocalTime:  true,
			Filename:   os.Getenv("LOG_ACCESS_PATH"),
			MaxSize:    50,   // 一个文件最大为50M
			MaxBackups: 10,   // 最多同时保存10份文件
			MaxAge:     3,    // 一个文件最多同时存在3天
			Compress:   true, // 压缩
		}
		writers := []io.Writer{
			logger,
			os.Stdout,
		}
		fileAndStdoutWriter := io.MultiWriter(writers...)
		AccessLog.SetOutput(fileAndStdoutWriter)
	})
}
