package config

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

var (
	OpenRegistration      = false
	DataHome              = "/usr/local/amuse"
	Port             uint = 5008
	Address               = "127.0.0.1"
	TmdbApiKey            = ""
)

func ReadConfig(path string) error {
	file, err := os.Open(path)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		} else {
			fmt.Printf("error opening configuration %v\n", err)
			return err
		}
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		assignment := strings.Split(line, "=")
		variable := strings.Trim(assignment[0], " ")
		value := strings.Trim(assignment[1], " ")
		switch variable {
		case "OpenRegistration":
			OpenRegistration = value == "true"
		case "DataHome":
			DataHome = value
		case "Address":
			Address = value
		case "TmdbApiKey":
			TmdbApiKey = value
		case "Port":
			fmt.Sscanf(value, "%d", &Port)
		}
	}

	if err := scanner.Err(); err != nil {
		fmt.Printf("error reading configuration %v\n", err)
		return err
	}
	return nil
}
