package db

import (
	"fmt"

	"mtp2_if/config"
	"mtp2_if/logger"

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

//var driverName = "oci8"
//var dataSourceName = "mtp2_test18/muchinfo@192.168.31.117:1521/orcl"

// Engine DB Engine
var Engine *xorm.Engine

// InitDbEngine 创建数据库驱动
func InitDbEngine() error {
	driverName := config.SerCfg.GetDbDriver()
	dataSourceName := config.SerCfg.GetDbSource()

	var err error
	Engine, err = xorm.NewOracle(driverName, dataSourceName)
	if err != nil {
		fmt.Println("create db 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
}

// GetEngine GetEngine
func GetEngine() *xorm.Engine {
	return Engine
}

// Close Close
func Close() {
	Engine.Close()
}
