package config

import (
	"fmt"
	"os"

	"github.com/BurntSushi/toml"
)

type Config struct {
	OpenRGB OpenRGBConfig `toml:"openrgb"`
	Relay   RelayConfig   `toml:"relay"`
	Monitor MonitorConfig `toml:"monitor"`
}

type OpenRGBConfig struct {
	Host    string `toml:"host"`
	Port    int    `toml:"port"`
	Enabled bool   `toml:"enabled"`
}

type RelayConfig struct {
	Device  string `toml:"device"`
	Channel int    `toml:"channel"`
	Baud    int    `toml:"baud"`
	Enabled bool   `toml:"enabled"`
}

type MonitorConfig struct {
	// Which D-Bus signals to listen on. Options: "screensaver", "logind", "all"
	Method string `toml:"method"`
}

func Load(path string) (*Config, error) {
	cfg := &Config{
		OpenRGB: OpenRGBConfig{
			Host:    "localhost",
			Port:    6742,
			Enabled: true,
		},
		Relay: RelayConfig{
			Device:  "/dev/ttyUSB0",
			Channel: 1,
			Baud:    9600,
			Enabled: true,
		},
		Monitor: MonitorConfig{
			Method: "all",
		},
	}

	data, err := os.ReadFile(path)
	if err != nil {
		if os.IsNotExist(err) {
			return cfg, nil
		}
		return nil, fmt.Errorf("read config: %w", err)
	}

	if err := toml.Unmarshal(data, cfg); err != nil {
		return nil, fmt.Errorf("parse config: %w", err)
	}

	return cfg, nil
}
