package zimbra

import (
	"bytes"
	"encoding/xml"
	"io"
	"os"
	"path/filepath"
)

type Localconfig struct {
	XMLName         xml.Name         `xml:"localconfig"`
	LocalconfigKeys []LocalconfigKey `xml:"key"`
}

type LocalconfigKey struct {
	XMLName xml.Name `xml:"key"`
	Name    string   `xml:"name,attr"`
	Value   string   `xml:"value"`
}

var localConfigData map[string]string

func ReadLocalConfig(basePath string) error {

	filePath := filepath.Join(basePath, "conf/localconfig.xml")
	xmlFile, errOpen := os.Open(filePath)
	if errOpen != nil {
		return errOpen
	}
	defer xmlFile.Close()

	var buf bytes.Buffer
	_, errCopy := io.Copy(&buf, xmlFile)
	if errCopy != nil {
		return errCopy

	}

	var data Localconfig

	errXml := xml.Unmarshal(buf.Bytes(), &data)
	if errXml != nil {
		return errXml
	}

	localConfigData = make(map[string]string)

	for _, key := range data.LocalconfigKeys {
		localConfigData[key.Name] = key.Value
	}

	return nil
}

func Get(param string) (string, bool) {

	value, ok := localConfigData[param]

	return value, ok
}
