package common

import (
	"io"
	"log"
	"os"
	"time"
)

// flags and prefix
const (
	flag       = log.Ldate | log.Ltime | log.Lshortfile
	preDebug   = "[DEBUG] "
	preInfo    = "[INFO] "
	preWarning = "[WARNING] "
	preError   = "[ERROR] "
)

// diff logger and output log file
var (
	logFile        io.Writer
	debugLogger    *log.Logger
	infoLogger     *log.Logger
	warningLogger  *log.Logger
	errorLogger    *log.Logger
	defaultLogFile = "./logs/web.log"
)

func createFile() {
	var err error
	logFile, err = os.OpenFile(defaultLogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		logFile, err = os.OpenFile(defaultLogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
		if err != nil {
			log.Fatalf("create log file err %+v", err)
		}
	}

	debugLogger = log.New(io.MultiWriter(os.Stdout, logFile), preDebug, flag)
	infoLogger = log.New(logFile, preInfo, flag)
	warningLogger = log.New(logFile, preWarning, flag)
	errorLogger = log.New(logFile, preError, flag)
}

// init for logger
func init() {
	createFile()
}

// Debug logger
func Debug(format string, v ...interface{}) {
	debugLogger.Printf(format, v...)
}

func Info(format string, v ...interface{}) {
	infoLogger.Printf(format, v...)
}

func Warning(format string, v ...interface{}) {
	warningLogger.Printf(format, v...)
}

func Error(format string, v ...interface{}) {
	errorLogger.Printf(format, v...)
}

// set output file
func setOutputPath(path string) {
	var err error
	logFile, err = os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatalf("create log file err %+v", err)
	}
	debugLogger = log.New(logFile, preDebug, flag)
	infoLogger = log.New(logFile, preInfo, flag)
	warningLogger = log.New(logFile, preWarning, flag)
	errorLogger = log.New(logFile, preError, flag)
}

func SetFlags(flag int) {
	debugLogger.SetFlags(flag)
	infoLogger.SetFlags(flag)
	warningLogger.SetFlags(flag)
	errorLogger.SetFlags(flag)
}

func RenameLogFile() {
	if _, err := os.Stat(defaultLogFile); os.IsNotExist(err) {
		Info("文件不存在")
		return
	}

	// 重命名文件
	err := os.Rename(defaultLogFile, "./logs/"+time.Now().Format("2006-01-02")+"-info.log")
	if err != nil {
		Info("重命名失败：", err)
	} else {
		Info("重命名成功")
		createFile()
	}
}
