package zciyon

import (
	"bufio"
	"os"
	"strings"
)

// toml
type CiyINI struct {
	filePath string
	sections map[string]map[string]string
}

func NewCiyINI(filepath string) (*CiyINI, error) {
	ini := &CiyINI{}
	ini.filePath = filepath
	ini.sections = make(map[string]map[string]string)

	f, err := os.Open(filepath)
	if err != nil {
		return ini, err
	}
	defer f.Close()

	scanner := bufio.NewScanner(f)
	scanner.Split(bufio.ScanLines)

	nowsection := ""
	ini.sections[nowsection] = map[string]string{}
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if strings.TrimSpace(line) == "" {
			continue
		}
		if strings.HasPrefix(line, "[") {
			nowsection = strings.TrimSpace(line[1 : len(line)-1])
			if ini.sections[nowsection] == nil {
				ini.sections[nowsection] = map[string]string{}
			}
		} else {
			ind := strings.Index(line, "=")
			if ind == -1 {
				ini.sections[nowsection][line] = "!!null!!"
			} else {
				val := strings.TrimSpace(line[ind+1:])
				line = strings.TrimSpace(line[:ind])
				ini.sections[nowsection][line] = val
			}
		}
	}
	return ini, nil
}

func (thos *CiyINI) GetKey(section, key, def string) string {
	if vkey, ok := thos.sections[section]; ok {
		if val, ok := vkey[key]; ok {
			return val
		}
	}
	return def
}
func (thos *CiyINI) GetKeyint(section, key string, def int) int {
	if vkey, ok := thos.sections[section]; ok {
		if val, ok := vkey[key]; ok {
			return Toint(val)
		}
	}
	return def
}
func (thos *CiyINI) GetSection(section string) map[string]string {
	if vkey, ok := thos.sections[section]; ok {
		return vkey
	}
	return nil
}

func (thos *CiyINI) SetKey(section, key string, newval any) {
	if _, ok := thos.sections[section]; !ok {
		thos.sections[section] = map[string]string{}
	}
	if _, ok := thos.sections[section][key]; !ok {
		thos.sections[section][key] = ""
	}
	val := Tostr(newval)
	if thos.sections[section][key] != val {
		thos.sections[section][key] = val
	}
}
func (thos *CiyINI) Save() error {
	text := ""
	for key, val := range thos.sections[""] {
		if val == "!!null!!" {
			text += key + "\n"
		} else {
			text += key + "=" + val + "\n"
		}
	}
	for section, kvs := range thos.sections {
		if section == "" {
			continue
		}
		text += "\n[" + section + "]\n"
		for key, val := range kvs {
			if val == "!!null!!" {
				text += key + "\n"
			} else {
				text += key + "=" + val + "\n"
			}
		}
	}
	err := FileSave(thos.filePath, text)
	if err != nil {
		return err
	}
	return nil
}
