package config

import (
	"fmt"
	"os"
	"path/filepath"
	//"errors"
	"flag"

	"github.com/go-yaml/yaml"
)

const (
	defaultPort int = 9001
)

type ServiceConfig struct {
	PortNum    int    `json:"port"    yaml:"port"`
	WebDir     string `json:"webdir"  yaml:"webdir"`
	AccessPath string `json:"accessLog"  yaml:"accessLog"`
}

type Config struct {
	Service ServiceConfig `json:"service" yaml:"service"`
	LogPath string        `json:"logfile"  yaml:"logfile"`
	RunPath string        `json:"runfile"  yaml:"runfile"`
	Daemon  bool          `json:"daemon"   yaml:"daemon"`
	User    string        `yaml:"user"         json:"user"`
	Group   string        `yaml:"group"        json:"group"`
	Debug   bool          `yaml:"debug"        json:"debug"`
}

func NewConfig() *Config {
	conf := &Config{
		Service: ServiceConfig{
			PortNum: defaultPort,
			WebDir:  webdir,
		},
		LogPath: logPath,
		RunPath: runPath,
		User:    user,
		Group:   group,
	}
	return conf
}

func (conf *Config) ReadFile() error {
	var err error

	confBytes, err := os.ReadFile(configPath)
	if err != nil {
		return err
	}
	err = yaml.Unmarshal(confBytes, conf)
	if err != nil {
		return err
	}
	return err
}

func (conf *Config) ReadEnv() error {
	var err error
	return err
}

func (conf *Config) ReadOpts() error {
	var err error

	exeName := filepath.Base(os.Args[0])

	flag.IntVar(&conf.Service.PortNum, "port", conf.Service.PortNum, "listen port")
	flag.BoolVar(&conf.Daemon, "daemon", conf.Daemon, "run as daemon")

	help := func() {
		fmt.Println("")
		fmt.Printf("Usage: %s [option]\n", exeName)
		fmt.Println("")
		fmt.Println("Options:")
		flag.PrintDefaults()
		fmt.Println("")
	}
	flag.Usage = help
	flag.Parse()

	return err
}

func (conf *Config) Yaml() (string, error) {
	var err error
	var res string
	yamlBytes, err := yaml.Marshal(conf)
	if err != nil {
		return res, err
	}
	res = string(yamlBytes)
	return res, err
}
