package server

import (
	"io"
	"os"
	"strconv"

	"github.com/pelletier/go-toml/v2"
)

type Config struct {
	SiteName string       `toml:"siteName"`
	HTTP     ConfigHTTP   `toml:"http"`
	WebRTC   ConfigWebRTC `toml:"WebRTC"`
}

type ConfigHTTP struct {
	ListenAddr string `json:"ListenAddr" toml:"ListenAddr"`
}

type ConfigWebRTC struct {
	UDPMin int `toml:"UDPMin"`
	UDPMax int `toml:"UDPMax"`
}

func DefaultConfig() *Config {
	return &Config{
		SiteName: "ministream",
		HTTP: ConfigHTTP{
			ListenAddr: ":8080",
		},
		WebRTC: ConfigWebRTC{
			UDPMin: 50000,
			UDPMax: 50050,
		},
	}
}

func (c *Config) OverrideFromEnv() {
	if siteName, ok := os.LookupEnv("MINISTREAM_SITENAME"); ok {
		c.SiteName = siteName
	}

	if httpAddr, ok := os.LookupEnv("MINISTREAM_HTTP_LISTENADDR"); ok {
		c.HTTP.ListenAddr = httpAddr
	}

	if value, ok := os.LookupEnv("MINISTREAM_WEBRTC_UDPMIN"); ok {
		min, err := strconv.Atoi(value)
		if err != nil {
			panic("MINISTREAM_WEBRTC_UDPMIN is invalid")
		}
		c.WebRTC.UDPMin = min
	}
	if value, ok := os.LookupEnv("MINISTREAM_WEBRTC_UDPMAX"); ok {
		max, err := strconv.Atoi(value)
		if err != nil {
			panic("MINISTREAM_WEBRTC_UDPMAX is invalid")
		}
		c.WebRTC.UDPMin = max
	}
}

func ConfigFromReader(r io.Reader) (*Config, error) {
	var c Config

	err := toml.NewDecoder(r).Decode(&c)
	if err != nil {
		return nil, err
	}

	return &c, nil
}

func ConfigFromFile(path string) (*Config, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	return ConfigFromReader(f)
}

func ConfigFromDefault() (*Config, error) {
	var config *Config
	defaultPaths := []string{
		"ministream.toml",
	}

	for _, p := range defaultPaths {
		c, err := ConfigFromFile(p)
		if err != nil {
			continue
		}
		config = c
		break
	}

	if config == nil {
		config = DefaultConfig()
	}

	config.OverrideFromEnv()

	return config, nil
}