package main

import (
	"io"
	"os"
	"time"

	"github.com/natefinch/lumberjack"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"iwarma.ru/console/correlator/config"
)

func getLevel() log.Level {
	level := viper.GetInt(config.LogLevel)

	switch level {
	case 0:
		return log.PanicLevel
	case 1:
		return log.FatalLevel
	case 2:
		return log.ErrorLevel
	case 3:
		return log.WarnLevel
	case 4:
		return log.InfoLevel
	case 5:
		return log.DebugLevel
	case 6:
		return log.TraceLevel
	}
	return log.InfoLevel
}

func initLogging() error {
	lumberjackLogrotate := &lumberjack.Logger{
		Filename:   viper.GetString(config.LogFileName),
		MaxSize:    viper.GetInt(config.LogMaxSize),
		MaxBackups: viper.GetInt(config.LogMaxBkup),
		MaxAge:     viper.GetInt(config.LogMaxAge),
		Compress:   viper.GetBool(config.LogCompress),
	}

	if viper.GetString(config.LogFormatter) == "json" {
		log.SetFormatter(&log.JSONFormatter{TimestampFormat: time.RFC3339})
	} else {
		log.SetFormatter(&log.TextFormatter{TimestampFormat: time.RFC3339, ForceColors: viper.GetBool(config.LogForceColors)})
	}

	logMultiWriter := io.MultiWriter(os.Stdout, lumberjackLogrotate)
	log.SetOutput(logMultiWriter)

	log.SetLevel(getLevel())

	return nil
}
