package main

import (
	"errors"
	"github.com/BurntSushi/toml"
	"net"
	"os"
	"strings"
)

var (
	config *Config
)

type server struct {
	Addr, Mode string
}

type Loggerger struct {
	File, Level string
	Console     bool
}

type engine struct {
	Dictionary          string
	Stoptoken           string
	IndexType           int
	ShardsNum           int
	OutputOffset        int
	MaxOutput           int
	Persistent          bool
	PersistentEngine    string
	PersistentFolder    string
	PersistentShardsNum int
}

type Config struct {
	Server server
	Logger Loggerger
	Engine engine
}

func loadConfig(from string) (*Config, error) {
	var config Config
	if _, err := toml.DecodeFile(from, &config); err != nil {
		return nil, err
	}
	err := checkConfig(&config)
	if err != nil {
		return nil, err
	}

	return &config, nil
}

func checkConfig(c *Config) error {
	// server
	_, err := net.ResolveTCPAddr("tcp", c.Server.Addr)
	if err != nil {
		return err
	}
	c.Server.Mode = strings.ToLower(c.Server.Mode)
	if c.Server.Mode != "debug" && c.Server.Mode != "release" {
		return errors.New("invalid server.Mode config")
	}
	//Loggerger
	c.Logger.Level = strings.ToLower(c.Logger.Level)
	if c.Logger.Level != "debug" && c.Logger.Level != "info" && c.Logger.Level != "warn" && c.Logger.Level != "error" {
		return errors.New("invalid Loggerger.Level config")
	}

	// engine
	if !exists(c.Engine.Dictionary) {
		return errors.New("dictionary not exists")
	}
	if !exists(c.Engine.Stoptoken) {
		return errors.New("stoptoken not exists")
	}
	if !exists(c.Engine.PersistentFolder) {
		return errors.New("PersistentFolder not exists")
	}
	if c.Engine.IndexType != 0 && c.Engine.IndexType != 1 && c.Engine.IndexType != 2 {
		return errors.New("invalid engine.index_type")
	}
	if c.Engine.PersistentEngine != "kv" && c.Engine.PersistentEngine != "bolt" {
		return errors.New("invalid engine.persistent_engine")
	}
	return nil
}

func exists(fileOrDir string) bool {
	_, err := os.Stat(fileOrDir)
	return err == nil
}
