package server

import (
	"fmt"
	"net"
	"os"
	"time"

	cnf "git.ego.freeddns.org/egommerce/go-api-pkg/config"
)

const (
	defName             = "identity-svc"
	defDomain           = "identity-svc"
	defCacheAddr        = "api-cache:6379"
	defCacheUsername    = "default"
	defCachePassword    = "12345678"
	defDbURL            = "postgres://postgres:12345678@db-postgres:5432/egommerce"
	defEventBusURL      = "amqp://guest:guest@api-eventbus:5672"
	defKVNmspc          = "dev.egommerce/service/identity"
	defLoggerAddr       = "api-logger:24224"
	defNetAddr          = ":443"
	defMongoDbURL       = "mongodb://mongodb:12345678@mongo-db:27017"
	defPathPrefix       = "/identity"
	defEbEventsExchange = "api-events"
	defEbEventsQueue    = "identity-svc"
)

type Config struct {
	ID         string
	Name       string
	Domain     string
	NetAddr    string
	PathPrefix string

	IdleTimeout  time.Duration // miliseconds
	ReadTimeout  time.Duration // miliseconds
	WriteTimeout time.Duration // miliseconds

	LoggerAddr       string `json:"logger_addr"`
	DbURL            string `json:"db_url"`
	CacheAddr        string `json:"cache_addr"`
	CacheUsername    string `json:"cache_username"`
	CachePassword    string `json:"cache_password"`
	MongoDbUrl       string `json:"mongodb_url"`
	EventBusURL      string `json:"eventbus_url"`
	EventBusExchange string `json:"eventbus_exchange"`
	EventBusQueue    string `json:"eventbus_queue"`
}

func NewConfig(name string) *Config {
	c := new(Config)

	c.ID, _ = os.Hostname()
	c.Name = name
	c.Domain = cnf.GetEnv("APP_DOMAIN", defDomain)
	c.NetAddr = cnf.GetEnv("SERVER_ADDR", defNetAddr)
	c.CacheAddr = cnf.GetEnv("API_CACHE_ADDR", defCacheAddr)
	c.CacheUsername = cnf.GetEnv("API_CACHE_USERNAME", defCacheUsername)
	c.CachePassword = cnf.GetEnv("API_CACHE_PASSWORD", defCachePassword)
	c.DbURL = cnf.GetEnv("API_DATABASE_URL", defDbURL)
	c.EventBusExchange = defEbEventsExchange
	c.EventBusURL = cnf.GetEnv("API_EVENTBUS_URL", defEventBusURL)
	c.LoggerAddr = cnf.GetEnv("API_LOGGER_ADDR", defLoggerAddr)
	c.PathPrefix = cnf.GetEnv("APP_PATH_PREFIX", defPathPrefix)

	return c
}

func (c *Config) GetAppFullName() string {
	return fmt.Sprintf("%s_%s", c.Name, c.ID)
}

func (c *Config) GetIP() string {
	host, _ := os.Hostname()
	ips, _ := net.LookupIP(host)
	// for _, ip := range ips {
	// 	return ip.String()
	// }

	return ips[0].String()
}

func (c *Config) GetArray() map[string]string { // FIXME fix types etc
	arr := make(map[string]string)
	arr["id"] = c.ID
	arr["name"] = c.Name
	arr["appFullname"] = c.GetAppFullName()
	arr["domain"] = c.Domain
	arr["ip"] = c.GetIP()
	arr["netAddr"] = c.NetAddr
	arr["pathPrefix"] = c.PathPrefix
	arr["cacheAddr"] = c.CacheAddr
	arr["cacheUsername"] = c.CacheUsername
	arr["cachePassword"] = c.CachePassword
	arr["dbURL"] = c.DbURL
	arr["eventBusExchange"] = c.EventBusExchange
	arr["eventBusURL"] = c.EventBusURL
	arr["loggerAddr"] = c.LoggerAddr

	return arr
}
