package config

import (
	"log"
	"os"
	"time"

	mysql2 "github.com/go-sql-driver/mysql"
	"github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var (
	DB       *gorm.DB
	LDB      *gorm.DB
	GDB1     *gorm.DB
	GDBGroup map[int]*gorm.DB
	AdminDB  *gorm.DB
)

func InitDatabase() {
	initAdminDB()
}

func initAdminDB() {
	connString := os.Getenv("ADMIN_MYSQL_DSN")
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level(这里记得根据需求改一下)
			IgnoreRecordNotFoundError: true,        // Ignore ErrRecordNotFound error for logger
			Colorful:                  false,       // Disable color
		},
	)

	db, err := gorm.Open(mysql.Open(connString), &gorm.Config{
		Logger:                 newLogger,
		SkipDefaultTransaction: true,
	})

	if connString == "" || err != nil {
		logrus.Fatalf("mysql lost: %v", err)
	}
	sqlDB, err := db.DB()
	if err != nil {
		logrus.Fatalf("mysql lost: %v", err)
	}

	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(20)
	sqlDB.SetConnMaxLifetime(2 * time.Hour)
	AdminDB = db
}

// GetDBName 获取数据库库名
func GetDBName(conn string) string {
	dsnConf, _ := mysql2.ParseDSN(conn)
	return dsnConf.DBName
}

func GetDBId(DB *gorm.DB) int {
	for k, db := range GDBGroup {
		if db == DB {
			return k
		}
	}
	return 0
}
