package config

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

func initEULA(serverFolder string) []ServerConfig {
	properties := []ServerConfig{}

	b, err := ioutil.ReadFile(serverFolder + "/eula.txt") // 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
}

//ReadEULA should exported.
func (mch *Handler) ReadEULA() bool {
	b, _ := strconv.ParseBool(mch.eula[0].value)
	return b
}

//WriteEULA should exported.
func (mch *Handler) WriteEULA(accept bool) bool {
	mch.eula[0].value = strconv.FormatBool(accept)
	return true
}

//SaveEULA is exported function
func (mch *Handler) SaveEULA() bool {
	TXT := "#By changing the setting below to TRUE you are indicating your agreement to our EULA (https://account.mojang.com/documents/minecraft_eula).\n"
	for _, line := range mch.eula {
		TXT += line.key + "=" + line.value + "\n"
	}
	err := ioutil.WriteFile(mch.serverFolder+"/eula.txt", []byte(TXT), 0777)
	if err != nil {
		fmt.Println(err)
	}
	return true
}

//there is no remove cuz EULA shouldn't be removed.
