package config

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"github.com/nats-io/nats.go"
	"github.com/spf13/viper"
	"log"
	"runtime"
)

type Config struct {
	Port     int       `json:"port,omitempty"`
	DataBase *DataBase `json:"database,omitempty"`
	MQ       *MQ       `json:"mq,omitempty"`
}

type DataBase struct {
	Name         string `json:"name,omitempty"`
	Host         string `json:"host,omitempty"`
	MaxOpenConns int    `json:"maxOpenConns,omitempty"`
	MaxIdleConns int    `json:"maxIdleConns,omitempty"`
}

type MQ struct {
	Name string `json:"name,omitempty"`
	Host string `json:"host,omitempty"`
}

var Conf *Config
var DB *sqlx.DB
var JS nats.JetStreamContext

func InitConf() {
	if runtime.GOOS=="linux"{
		viper.SetConfigFile("./config-linux.yaml")
	}else{
		viper.SetConfigFile("./config.yaml")
	}

	if err := viper.ReadInConfig(); err != nil {
		panic("Read file error:" + err.Error())
	}
	var config Config
	if err := viper.Unmarshal(&config); err != nil {
		panic("File exchange error:" + err.Error())
	}
	Conf = &config
}

func InitDataBase() {

	var err error
	DB, err = sqlx.Connect(Conf.DataBase.Name, Conf.DataBase.Host)
	if err != nil {
		log.Fatalf("connect DB failed, err:%v\n", err)
		return
	}
	DB.SetMaxOpenConns(Conf.DataBase.MaxOpenConns)
	DB.SetMaxIdleConns(Conf.DataBase.MaxOpenConns)
}

func InitMQ() {
	conn, err := nats.Connect(Conf.MQ.Host)
	if err != nil {
		fmt.Println(err)
	}
	js, _ := conn.JetStream(nats.PublishAsyncMaxPending(256))
	js.AddStream(&nats.StreamConfig{
		Name:     "EXAMS",
		Subjects: []string{"EXAMS.*"},
	})
	JS = js
}

func init() {
	// 1、初始化配置
	InitConf()

	// 2、初始化数据库
	InitDataBase()

	// 3、初始化MQ
	InitMQ()
}
