package config

import (
	"fmt"
	"io/ioutil"
	"regexp"
	"strings"
)

//initProperties xxx
func initProperties(serverFolder string) []ServerConfig {
	properties := []ServerConfig{}

	b, err := ioutil.ReadFile(serverFolder + "/server.properties") // just pass the file name
	if err != nil {
		fmt.Print(err)
	}
	str := string(b) // convert content to a 'string'
	lines := strings.Split(str, "\n")

	for _, line := range lines {
		regex := regexp.MustCompile("^(.*)=(.*[^=]*)$")
		regexSubmatch := regex.FindStringSubmatch(line)
		if len(regexSubmatch) > 0 {
			item := ServerConfig{
				key:   regexSubmatch[1],
				value: regexSubmatch[2],
			}
			properties = append(properties, item)
		}
	}
	return properties
}

//ReadAllProperties is exported function
func (mch *Handler) ReadAllProperties() []ServerConfig {
	return mch.properties
}

//ChangeProperties is exported function
func (mch *Handler) ChangeProperties(inputKey string, inputValue string) bool {
	for i, item := range mch.properties {
		if strings.ToLower(inputKey) == strings.ToLower(item.key) {
			mch.properties[i].value = inputValue
		}
	}
	return true
}

//SaveProperties is exported function
func (mch *Handler) SaveProperties() bool {
	TXT := "#Minecraft server properties"
	for _, line := range mch.properties {
		TXT += line.key + "=" + line.value + "\n"
	}
	err := ioutil.WriteFile(mch.serverFolder+"/server.properties", []byte(TXT), 0777)
	if err != nil {
		fmt.Println(err)
	}
	return true
}

//There is no delete or add function because it is not necessary :)
