package logger


import (
	"fmt"
	"github.com/spf13/viper"
	"os"
	"github.com/sirupsen/logrus"
)


func Lgr(l *Log) {
	// The API for setting attributes is a little different than the package level
	// exported logger. See Godoc.
	var log = logrus.New()

	logLvl := viper.GetString("loglevel")
	setLogLeve(&logLvl, log)
	logDir := viper.GetString("logsdirectory")
	logFile := viper.GetString("logfile")
	logPath :=  logDir + "/" + logFile
	if _, err := os.Stat(logPath); os.IsNotExist(err) {
		os.Create(logPath)
	}
	// You could set this to any `io.Writer` such as a file
	logToFile(l, &logPath, log)
}

func logToFile(l *Log, logPath *string, log *logrus.Logger) {
	file, err := os.OpenFile(*logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err == nil {
		log.Out = file
		switch l.Type {
		case "info":
			log.WithFields(l.Fields).Info(l.LogDetail)
		case "warn":
			log.WithFields(l.Fields).Warn(l.LogDetail)
		case "error":
			log.WithFields(l.Fields).Error(l.LogDetail)
		default:
			fmt.Println("¯\\_(ツ)_/¯")
		}
	} else {
		fmt.Println(err)
		log.Info("Failed to log to file, using default stderr")
	}
}

func setLogLeve(l *string, lg *logrus.Logger) {
	switch *l {
	case "debug":
		lg.Level = logrus.DebugLevel
	default:
		lg.Level = logrus.InfoLevel
	}

}


type Log struct {
	Type string
	Fields logrus.Fields
	LogDetail string
}