//   Sofaraum server is the server which collects the statistics
//   for the sofaraum-heatmap application.
//   Copyright 2018 K.Langenberg and contributors. All rights reserved.
//
//   This program is free software: you can redistribute it and/or modify
//   it under the terms of the GNU General Public License as published by
//   the Free Software Foundation, either version 3 of the License, or
//   (at your option) any later version.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program.  If not, see <https://www.gnu.org/licenses/>.

package config

import (
	"crypto/rand"
	"fmt"
	"github.com/spf13/viper"
	"os"
	"path/filepath"
	"strings"
)

// InitConfig initializes the config, sets defaults etc.
func InitConfig() (err error) {

	// Set defaults
	// Service config
	random, err := random(32)
	if err != nil {
		return err
	}

	// Service
	viper.SetDefault("service.JWTSecret", random)
	viper.SetDefault("service.interface", ":1073")
	viper.SetDefault("service.frontendurl", "")
	ex, err := os.Executable()
	if err != nil {
		panic(err)
	}
	exPath := filepath.Dir(ex)
	viper.SetDefault("service.rootpath", exPath)
	viper.SetDefault("service.pagecount", 50)
	// Database
	viper.SetDefault("database.type", "sqlite")
	viper.SetDefault("database.host", "localhost")
	viper.SetDefault("database.user", "sofaraum")
	viper.SetDefault("database.password", "")
	viper.SetDefault("database.database", "sofaraum")
	viper.SetDefault("database.path", "./sofaraum.db")
	viper.SetDefault("database.showqueries", false)
	viper.SetDefault("database.openconnections", 100)
	// Cacher
	viper.SetDefault("cache.enabled", false)
	viper.SetDefault("cache.type", "memory")
	viper.SetDefault("cache.maxelementsize", 1000)
	viper.SetDefault("cache.redishost", "localhost:6379")
	viper.SetDefault("cache.redispassword", "")

	// Init checking for environment variables
	viper.SetEnvPrefix("sofaraum")
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	viper.AutomaticEnv()

	// Load the config file
	viper.AddConfigPath(".")
	viper.SetConfigName("config")
	err = viper.ReadInConfig()
	if err != nil {
		fmt.Println(err)
		fmt.Println("Using defaults.")
	}

	return nil
}

func random(length int) (string, error) {
	b := make([]byte, length)
	if _, err := rand.Read(b); err != nil {
		return "", err
	}

	return fmt.Sprintf("%X", b), nil
}
