package podman

import (
	"dcu-container-toolkit/pkg/config/engine"
	"fmt"

	"gopkg.in/ini.v1"
)

type Config struct {
	File *ini.File
}
const (
    defaultDTKRuntimeExpecutablePath = "/usr/bin/dcu-container-runtime"
)
var _ engine.Interface = (*Config)(nil)

func New(opts ...Option) (engine.Interface, error) {
	b := &builder{}
	for _, opt := range opts {
		opt(b)
	}

	return b.build()
}

func (c *Config) AddRuntime(name string, path string, setAsDefault bool, _ ...map[string]interface{}) error {
	if c == nil {
		return fmt.Errorf("config is nil")
	}

	cfg := c.File
	runc := cfg.Section("engine").Key("runtime").String()
	if runc == "" {
		containers := cfg.Section("containers")
		containers.Key("default_capabilities").SetValue(`["NET_RAW", "CHOWN", "DAC_OVERRIDE", "FOWNER", "FSETID", "KILL", "NET_BIND_SERVICE", "SETFCAP", "SETGID", "SETPCAP", "SETUID", "SYS_CHROOT"]`)
		containers.Key("default_sysctls").SetValue(`["net.ipv4.ping_group_range=0 0"]`)
		containers.Key("log_driver").SetValue("k8s-file")

		// engine section
		engine := cfg.Section("engine")
		engine.Key("events_logger").SetValue("file")
		engine.Key("runtime").SetValue("runc")

		
		cfg.NewSection("engine.runtimes")
		cfg.NewSection("engine.volume_plugins")
		cfg.NewSection("farms")
		cfg.NewSection("machine")

		// network section
		network := cfg.Section("network")
		network.Key("network_backend").SetValue("cni")

		// secrets sections
		cfg.NewSection("secrets")
		cfg.NewSection("secrets.opts")

	}
	if setAsDefault {
		cfg.Section("engine").Key("runtime").SetValue(defaultDTKRuntimeExpecutablePath)
	}
	c.File = cfg
	return nil
}

func (c Config) DefaultRuntime() string {
	runc := c.File.Section("engine").Key("runtime").String()
	if runc == "" {
		return ""
	}
	return runc
}

func (c *Config) RemoveRuntime(name string) error {
	if c == nil {
		return nil
	}
	cfg := c.File
	if runc := cfg.Section("engine").Key("runtime").String(); runc != "" {
		cfg.DeleteSection("engine.runtimes")
	}
	c.File = cfg
	return nil
}

func (c *Config) Set(key string, value interface{}) {
	cfg := c.File
	if str, ok := value.(string); ok {
	    cfg.Section("engine").Key(key).SetValue(str)
        } else {
      	    fmt.Println("key %s value is not string", key)
        }
	c.File = cfg
}

func (c *Config) Save(path string) (int64, error) {
	cfg := c.File
	return 0, cfg.SaveTo(path)
}

