package mysql

import (
	"ai_developer_admin/models"
	"fmt"
	"github.com/beego/beego/orm"
	"github.com/beego/beego/v2/core/logs"
	beego "github.com/beego/beego/v2/server/web"
	_ "github.com/go-sql-driver/mysql"
	"sync"
)

type Singleton struct {
	Ormer orm.Ormer
}

var instance *Singleton
var once sync.Once

func GetMysqlInstace() *Singleton {
	once.Do(func() {
		instance = &Singleton{
			Ormer: orm.NewOrm(),
		}
	})
	return instance
}

func init() {
	logs.Debug("mysql lib init")
	//return
	orm.Debug = true
	if err := orm.RegisterDriver("mysql", orm.DRMySQL); err != nil {
		logs.Error(err.Error())
	}

	orm.RegisterModel(new(models.User))
	//orm.RegisterModel(new(models.App))
	orm.RegisterModel(new(models.ChargeRecord))
	orm.RegisterModel(new(models.UserLevel))
	orm.RegisterModel(new(models.ApiKey))
	orm.RegisterModel(new(models.JwtToken))
	orm.RegisterModel(new(models.TaskType))
	orm.RegisterModel(new(models.UserLevelTaskType))
	orm.RegisterModel(new(models.Category))
	orm.RegisterModel(new(models.Whitelist))
	orm.RegisterModel(new(models.Computility))
	orm.RegisterModel(new(models.Favorite))
	orm.RegisterModel(new(models.TaskTypeVersion))

	logs.Debug("AppConfig", beego.AppConfig)

	dbuser, _ := beego.AppConfig.String("mysqluser")
	dbpass, _ := beego.AppConfig.String("mysqlpass")
	dbhost, _ := beego.AppConfig.String("mysqlhost")
	dbport, _ := beego.AppConfig.String("mysqlport")
	dbname, _ := beego.AppConfig.String("mysqldb")
	logs.Debug("mysql info", dbuser, dbpass, dbhost, dbport, dbname)

	dbURL := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", dbuser, dbpass, dbhost, dbport, dbname)
	logs.Debug("Will connect to mysql url", dbURL)

	if err := orm.RegisterDataBase("default", "mysql", dbURL); err != nil {
		logs.Error(err.Error())
		panic(err.Error())
	}
	orm.SetMaxIdleConns("default", 10)
	orm.SetMaxOpenConns("default", 100)
}

func Ping() error {
	db, err := orm.GetDB("default")
	if err != nil {
		return err
	}
	return db.Ping()
}
