package db

import (
	"fmt"
	"mtp2_if/config"
	"mtp2_if/logger"

	"github.com/xormplus/core"
	"github.com/xormplus/xorm"
	"github.com/xormplus/xorm/log"
)

// MySQLEngine MySQL Engine
var MySQLEngine *xorm.Engine

// InitMySQLDbEngine 创建数据库驱动
func InitMySQLDbEngine() error {
	host := config.SerCfg.GetMySQLHost()
	port := config.SerCfg.GetMySQLPort()
	dbname := config.SerCfg.GetMySQLDBName()
	username := config.SerCfg.GetMySQLUsername()
	password := config.SerCfg.GetMySQLPassword()
	dataSourceName := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8", username, password, host, port, dbname)

	var err error
	MySQLEngine, err = xorm.NewEngine("mysql", dataSourceName)
	if err != nil {
		fmt.Println("create mysql engine failed:", err)
		return err
	}

	Engine.SetMaxIdleConns(10)
	Engine.SetMaxOpenConns(100)

	// 将SQL写到日志文件
	logger := log.NewSimpleLogger(logger.GetLogWriter())
	Engine.SetLogger(logger)
	// 将SQL打印到Console
	Engine.ShowSQL(true)
	Engine.SetTableMapper(core.SameMapper{})

	return nil
}

// GetMySQLEngine GetMySQLEngine
func GetMySQLEngine() *xorm.Engine {
	return MySQLEngine
}

// CloseMySQL CloseMySQL
func CloseMySQL() {
	MySQLEngine.Close()
}
