package main

import (
	"fmt"
	"os"
	"strings"
)

type LogLevel int

const (
	LevelDebug LogLevel = iota
	LevelInfo
	LevelWarn
	LevelError
	LevelNone
)

var logLevelNames = map[LogLevel]string{
	LevelDebug: "DEBUG",
	LevelInfo:  "INFO",
	LevelWarn:  "WARN",
	LevelError: "ERROR",
	LevelNone:  "NONE",
}

var currentLevel = LevelInfo

func SetLogLevel(level LogLevel) {
	currentLevel = level
}

func ParseLogLevel(s string) (LogLevel, error) {
	switch strings.ToUpper(s) {
	case "DEBUG":
		return LevelDebug, nil
	case "INFO":
		return LevelInfo, nil
	case "WARN":
		return LevelWarn, nil
	case "ERROR":
		return LevelError, nil
	case "NONE":
		return LevelNone, nil
	default:
		return LevelInfo, fmt.Errorf("unknown log level: %s (valid: debug, info, warn, error, none)", s)
	}
}

func logDebug(format string, args ...interface{}) {
	if currentLevel <= LevelDebug {
		fmt.Fprintf(os.Stderr, "DEBUG: "+format+"\n", args...)
	}
}

func logInfo(format string, args ...interface{}) {
	if currentLevel <= LevelInfo {
		fmt.Fprintf(os.Stderr, format+"\n", args...)
	}
}

func logWarn(format string, args ...interface{}) {
	if currentLevel <= LevelWarn {
		fmt.Fprintf(os.Stderr, "WARN: "+format+"\n", args...)
	}
}

func logErrorf(format string, args ...interface{}) {
	if currentLevel <= LevelError {
		fmt.Fprintf(os.Stderr, "ERROR: "+format+"\n", args...)
	}
}
