package main

import (
	"fmt"
	"github.com/rs/zerolog"
	"gopkg.in/natefinch/lumberjack.v2"
	"io"
	"os"
	"path"
	"strings"
)

var (
	logger zerolog.Logger

	levelMap = map[string]zerolog.Level{
		"trace":   zerolog.TraceLevel,
		"debug":   zerolog.DebugLevel,
		"info":    zerolog.InfoLevel,
		"warn":    zerolog.WarnLevel,
		"error":   zerolog.ErrorLevel,
		"disable": zerolog.NoLevel,
	}
)

func initLogger(console bool, file string, level string) {
	if err := os.MkdirAll(path.Dir(file), 744); err != nil {
		fmt.Println("bad")
	}
	fileWriter := &lumberjack.Logger{
		Filename:   file,
		MaxBackups: 128,
		MaxSize:    10,
		MaxAge:     30,
	}
	var writers = []io.Writer{fileWriter}
	if console {
		writers = append(writers, zerolog.ConsoleWriter{Out: os.Stderr})
	}
	mw := zerolog.MultiLevelWriter(writers...)
	newlogger := zerolog.New(mw).With().Timestamp().Caller().Logger()

	lv, ok := levelMap[strings.ToLower(level)]
	if !ok {
		lv = zerolog.InfoLevel
	}
	zerolog.SetGlobalLevel(lv)

	logger = newlogger
}
