package fly

import (
	nested "github.com/antonfisher/nested-logrus-formatter"
	log "github.com/sirupsen/logrus"
	"io"
	//"log"
	"os"
)

var (
	logFlag   = false
	debugFlag = false
	logger    *log.Logger
	logName   = "flynet.log"
)

func InitLog() {
	logger = GetLogger()
}

func EnableLog(flag bool) {
	logFlag = flag
}

func EnableDebug(flag bool) {
	debugFlag = flag
}

// set log file name, which can include absolute path
func SetLogName(name string) {
	logName = name
}

// return a logger
func GetLogger() *log.Logger {
	if logger != nil {
		return logger
	}
	var f *os.File
	var err error
	if logFlag {
		f, err = os.OpenFile(logName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
		if err != nil {
			log.Println("create or open log file failed --->", err)
		}
	}
	var writers []io.Writer

	//if logFlag && debugFlag {
	//	writers = []io.Writer{f, os.Stdout}
	//} else if !logFlag && !debugFlag {
	//	writers = []io.Writer{}
	//} else if debugFlag {
	//	writers = []io.Writer{os.Stdout}
	//} else {
	//	writers = []io.Writer{f}
	//}

	if logFlag {
		writers = append(writers, f)
	}
	if debugFlag {
		writers = append(writers, os.Stdout)
	}
	targetWriter := io.MultiWriter(writers...)

	logs := log.New()
	logs.Out = targetWriter
	//logs := log.New(targetWriter, "", log.Ldate|log.Ltime)

	//logs.SetLevel(log.InfoLevel)
	logs.SetLevel(log.DebugLevel)
	logs.SetFormatter(&nested.Formatter{
		HideKeys:        true,
		FieldsOrder:     []string{"component", "category"},
		TimestampFormat: "2006-01-02 15:04:05",
	})

	//logs.SetReportCaller(true)
	return logs
}
