package log

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"

	logger "github.com/inconshreveable/log15"
	"github.com/k0kubun/pp"
)

// SetLogger set logger
func SetLogger(logDir string, quiet, debug, logJSON bool) {
	stderrHundler := logger.StderrHandler
	logFormat := logger.LogfmtFormat()
	if logJSON {
		logFormat = logger.JsonFormatEx(false, true)
		stderrHundler = logger.StreamHandler(os.Stderr, logFormat)
	}

	lvlHundler := logger.LvlFilterHandler(logger.LvlInfo, stderrHundler)
	if debug {
		lvlHundler = logger.LvlFilterHandler(logger.LvlDebug, stderrHundler)
	}
	if quiet {
		lvlHundler = logger.LvlFilterHandler(logger.LvlDebug, logger.DiscardHandler())
		pp.SetDefaultOutput(ioutil.Discard)
	}

	if _, err := os.Stat(logDir); os.IsNotExist(err) {
		if err := os.Mkdir(logDir, 0700); err != nil {
			logger.Error("Failed to create log directory", "err", err)
		}
	}
	var hundler logger.Handler
	if _, err := os.Stat(logDir); err == nil {
		logPath := filepath.Join(logDir, "cve-dictionary.log")
		hundler = logger.MultiHandler(
			logger.Must.FileHandler(logPath, logFormat),
			lvlHundler,
		)
	} else {
		hundler = lvlHundler
	}
	logger.Root().SetHandler(hundler)
}

// Debugf is wrapper function
func Debugf(format string, args ...interface{}) {
	logger.Debug(fmt.Sprintf(format, args...))
}

// Infof is wrapper function
func Infof(format string, args ...interface{}) {
	logger.Info(fmt.Sprintf(format, args...))
}

// Warnf is wrapper function
func Warnf(format string, args ...interface{}) {
	logger.Warn(fmt.Sprintf(format, args...))
}

// Errorf is wrapper function
func Errorf(format string, args ...interface{}) {
	logger.Error(fmt.Sprintf(format, args...))
}

// Fatalf is wrapper function
func Fatalf(format string, args ...interface{}) {
	logger.Crit(fmt.Sprintf(format, args...))
}
