package mysql

import (
	"crm-api/pkg/configs"
	"crm-api/pkg/lfshook"
	"fmt"
	"os"
	"syscall"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/sirupsen/logrus"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
)

var DBOrmInstance *xorm.Engine

func CreateDBInstance() {
	var err error
	// DBOrmInstance, err = xorm.NewEngine("sqlite3", "playcall.db")
	url := fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?charset=utf8",
		configs.ConfigGlobal.MysqlDBUser,
		// "coovox_admin",
		configs.ConfigGlobal.MysqlDBSecret,
		// "ZycooCoovoxDba42",
		configs.ConfigGlobal.MysqlDBHost,
		configs.ConfigGlobal.MysqlDBName,
	)
	lfshook.NewLogger().Infof("mysql url %s", url)
	DBOrmInstance, err = xorm.NewEngine("mysql", url)
	if err != nil {
		lfshook.NewLogger().Panic(err)
		return
	}
	err = DBOrmInstance.Ping()
	if err != nil {
		lfshook.NewLogger().Error("mysql ping error: ", err)
		syscall.Kill(syscall.Getpid(), syscall.SIGINT)
		return
	}
	if configs.ConfigGlobal.LogLevel >= logrus.DebugLevel {
		DBOrmInstance.ShowSQL(true)
	} else {
		info, err := os.Open(configs.ConfigGlobal.LogInfoPath)
		if err != nil {
			lfshook.NewLogger().Error(err.Error())
			return
		}
		DBOrmInstance.SetLogger(log.NewSimpleLogger(info))
	}
	DBOrmInstance.Dialect().URI().Timeout = 30 * time.Second
}
