package config

import (
	"log"
	"os"
	"strconv"
)

// getEnv returns value for give key from environment
// if key is not present in environment it returns defaultValue
func getEnv(key, defaultValue string) string {
	v := os.Getenv(key)
	if len(v) > 0 {
		return v
	}
	return defaultValue
}

// getEnvInt returns integer value for give key from environment
// if key is not present in environment it returns defaultValue
// if key cannot be parsed to integer function will panic
func getEnvInt(key string, defaultValue int) int {
	v := os.Getenv(key)
	if len(v) == 0 {
		return defaultValue
	}

	valInteger, err := strconv.Atoi(v)
	if err != nil {
		log.Fatalf("variable `%s` cannot be parsed to INTEGER", key)
	}

	return valInteger
}

// getEnvInt returns integer value for give key from environment
// if key is not present in environment it returns defaultValue
// if key cannot be parsed to integer function will panic
func getEnvBoolWithDefault(key string, defaultValue bool) bool {
	v := os.Getenv(key)
	if len(v) == 0 {
		return defaultValue
	}

	val, err := strconv.ParseBool(v)
	if err != nil {
		log.Fatalf("variable `%s` cannot be parsed to BOOL", key)
	}

	return val
}

// getEnv extracts the bool value from environment variable
func getEnvBool(env string) bool {
	envVal := mustGetEnv(env)
	value, err := strconv.ParseBool(envVal)

	if err != nil {
		value = false
	}

	return value
}

// mustGetEnv returns value for give key from environment
// if key is not present in environment function will panic
func mustGetEnv(key string) string {
	v := os.Getenv(key)
	if len(v) == 0 {
		log.Fatalf(" variable `%s` is not present in ENVIRONMENT", key)
	}
	return v
}
