package configs

import (
	"fmt"
	_ "github.com/glebarez/sqlite"
	"github.com/spf13/cast"
	"github.com/spf13/viper"

	"os"
	"xorm.io/xorm"
)

var (
	Server  ServerConfiguration
	Manager ServerManager
	Engine  *xorm.Engine
	//RedisDb *redis.Client
)

type ServerConfiguration struct {
	Port string `mapstructure:"port"`
	Host string `mapstructure:"host"`
}

type ServerManager struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func init() {
	LoadServerConfiguration()
	ConfigInit()
}

func LoadServerConfiguration() {
	//获取项目的执行路径
	path, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	config := viper.New()

	config.AddConfigPath(path + "/configs") //设置读取的文件路径
	config.SetConfigName("config")          //设置读取的文件名
	config.SetConfigType("yaml")            //设置文件的类型
	if err := config.ReadInConfig(); err != nil {
		panic(err)
	}
	portString := config.Get("server.port")
	if cast.ToString(portString) == "" {
		portString = "9777"
	}
	host := config.Get("server.host")

	Server = ServerConfiguration{
		Port: cast.ToString(portString),
		Host: cast.ToString(host),
	}
	//用户账号密码获取
	username := config.Get("server.manager.username")
	password := config.Get("server.manager.password")
	Manager = ServerManager{
		Username: cast.ToString(username),
		Password: cast.ToString(password),
	}
}

func ConfigInit() {
	//获取项目的执行路径
	path, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	config := viper.New()
	config.AddConfigPath(path + "/configs") //设置读取的文件路径
	config.SetConfigName("config")          //设置读取的文件名
	config.SetConfigType("yaml")            //设置文件的类型
	//尝试进行配置读取
	if err := config.ReadInConfig(); err != nil {
		panic(err)
	}
	Engine, err = xorm.NewEngine("sqlite", "./file/ark-tools.db")
	Engine.Ping() //连接测试
	//TODO  显示sql
	Engine.ShowSQL(true)
	Engine.Logger().ShowSQL(true)
	fmt.Println("xorm 数据库orm框架初始化成功")
}
