package environment

import (
	"log"
	"os"

	"github.com/aws/aws-sdk-go/aws/ec2metadata"
	"github.com/aws/aws-sdk-go/aws/session"
)

// Environment constants
const (
	prod     = "prod"
	dev      = "dev"
	localDev = "localDev"
)

var env string

var cachedHostname string

func init() {
	env = Environment()
	if env != localDev {
		sess, err := session.NewSession()
		if err != nil {
			log.Fatal("could not create session")
		}

		svc := ec2metadata.New(sess)
		hostname, err := svc.GetMetadata("hostname")
		if err != nil {
			log.Println("could not get instance metadata")
		}
		cachedHostname = hostname
	}
}

func Environment() string {
	if env != "" {
		return env
	}
	env = os.Getenv("ENVIRONMENT")
	if env == "" {
		env = localDev
	}
	return env
}

func IsDev() bool {
	return Environment() == dev
}

func IsProd() bool {
	return Environment() == prod
}

func IsLocal() bool {
	return Environment() == localDev
}

func HostAddress() string {
	if env == localDev {
		return os.Getenv("IP_WOULD_GO_HERE")
	}
	return cachedHostname
}
