package envtool

import (
	"os"
	"strconv"
	"time"
)

// GetEnv return enviroment variable or default value if not set
func GetEnv(name string, defaultValue string) string {
	value, ok := os.LookupEnv(name)
	if ok && len(value) > 0 {
		return value
	}
	return defaultValue
}

// GetEnvInt returns environment variable or default value if not set
func GetEnvInt(name string, defaultValue int) int {
	value, ok := os.LookupEnv(name)
	if ok && len(value) > 0 {
		i, err := strconv.Atoi(value)
		if err == nil {
			return i
		}
	}
	return defaultValue
}

// GetEnvInt returns environment variable or default value if not set
func GetEnvInt64(name string, defaultValue int64) int64 {
	value, ok := os.LookupEnv(name)
	if ok && len(value) > 0 {
		i, err := strconv.ParseInt(value, 10, 0)
		if err == nil {
			return i
		}
	}
	return defaultValue
}

// GetEnvBool returns environment variable or default value if not set
func GetEnvBool(name string, defaultValue bool) bool {
	value, ok := os.LookupEnv(name)
	if !ok {
		return defaultValue
	}
	val, err := strconv.ParseBool(value)
	if err != nil {
		return defaultValue
	}
	return val
}

func GetEnvDuration(name string, defaultValue time.Duration) time.Duration {
	value, ok := os.LookupEnv(name)
	if ok && len(value) > 0 {
		d, err := time.ParseDuration(value)
		if err == nil {
			return d
		}
	}
	return defaultValue
}
