package config

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var (
	AdminDB    *gorm.DB
	LogDBGroup map[int32]*gorm.DB
)

func InitDatabase() {
	initAdminDB()
	initLogDBGroup()
}

func initAdminDB() {
	connString := os.Getenv("ADMIN_MYSQL_DSN")
	AdminDB = connDB(connString)
}

func initLogDBGroup() {
	LogDBGroup = make(map[int32]*gorm.DB)

	// 游戏服数据库组，新加服务器时往后续就行
	// 当连续3各数据库都不存在时，停止遍历

	failNum := 0
	for i := 1; i < 10000; i += 1 {
		conn := os.Getenv(fmt.Sprintf("LOG%v_MYSQL_DSN", i))
		if conn == "" {
			failNum += 1
			if failNum > 3 {
				return
			}
			//logrus.Warnf("initSingleGraveDB empty index[%v] present, skipped..", index)
			continue
		}
		failNum = 0
		db := connDB(conn)
		LogDBGroup[int32(i)] = db
	}
}

func connDB(connString string) *gorm.DB {
	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)
	return db
}
