package main

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

func LoadConfig(path string) (map[string]string, error) {
	//Scan config file line by line
	configData := make(map[string]string)
	configText, err := ioutil.ReadFile(path)
	if err != nil {
		return configData, err
	}

	textReader := bufio.NewScanner(strings.NewReader(string(configText)))

	lineNumber := 0
	for textReader.Scan() {
		if textReader.Err() != nil {
			return configData, textReader.Err()
		}
		lineNumber++
		line := textReader.Text()

		//remove comments
		commentStart := strings.Index(line, "#")
		if commentStart >= 0 {
			line = line[0:commentStart]
		}

		//remove empty lines
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}

		//Detect invalid lines
		separator := strings.Index(line, "=")
		if separator < 0 {
			return configData, fmt.Errorf("Invalid data at line %d: %s", lineNumber, line)
		}

		key := line[0:separator]
		value := line[separator+1:]
		value = strings.TrimSpace(value)

		first := value[0]
		last := value[len(value)-1]

		if first == last && (first == '\'' || first == '"') {
			value = value[1 : len(value)-1]
		}

		configData[key] = value
	}

	return configData, textReader.Err()
}
