package environment

import (
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

func String(varname string, defaultValue string) string {
	input := os.Getenv(varname)
	if input == "" {
		return defaultValue
	}
	return input
}

// Accept a duration string e.g. "30s" "5m" with default on empty
func Duration(varname string, defaultDuration time.Duration) time.Duration {
	input := os.Getenv(varname)
	if input == "" {
		return defaultDuration
	}
	d, err := time.ParseDuration(input)
	if err != nil {
		log.Printf("Could not parse duration %s: %s", varname, err.Error())
		os.Exit(1)
	}
	return d
}

// Accept a variety of strings representing a boolean value.
// allowBlankString allows the blank value to be used as "false"
func Bool(varname string, allowBlankString bool) bool {
	input := os.Getenv(varname)
	switch strings.ToLower(input) {
	case "yes", "y":
		return true
	case "no", "n":
		return false
	default:
		// ParseBool handles variants of t/f and true/false
		v, err := strconv.ParseBool(input)
		if err != nil {
			if input == "" && allowBlankString {
				return false
			}

			log.Printf("Could not parse bool %s: %s", varname, err.Error())
			os.Exit(1)
		}
		return v
	}
}
