package models

import (
	"github.com/astaxie/beego/config"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
)

var (
	DBEngine *xorm.Engine
)

func init() {
	DBEngine = NewDBEngine()
}

// NewDBEngine 初始化数据库连接
func NewDBEngine() *xorm.Engine {
	dbType := "mysql"
	dns := getMySQLDNS()

	engine, err := xorm.NewEngine(dbType, dns)
	// dao.ShowSQL()

	if err != nil {
		panic(err)
	}

	return engine
}

func getMySQLDNS() string {
	dbconf, _ := config.NewConfig("ini", "conf/db.conf")

	conProt := dbconf.DefaultString("con_protocol", "tcp")
	dbAddr := dbconf.DefaultString("db_addr", "localhost")
	dbPort := dbconf.DefaultString("db_port", "3306")
	userName := dbconf.DefaultString("username", "root")
	password := dbconf.String("password")
	database := dbconf.String("database")
	charSet := dbconf.DefaultString("char_set", "utf8")

	dns := userName

	if len(password) > 0 {
		dns += ":" + password
	}

	dns += "@" + conProt + "(" + dbAddr + ":" + dbPort + ")" + "/" + database + "?charset=" + charSet

	return dns
}
