package orm

import (
	"PPOSUtils/utils"

	"xorm.io/xorm"
)

func NewDB(engine *xorm.Engine, injectionMp utils.Mp) *DataBase {
	_db := &DataBase{
		engine:      engine,
		injectionMp: injectionMp, //
	}
	return _db
}

type DataBase struct {
	engine                 *xorm.Engine
	injectionMp            utils.Mp //注入的隔离字段
	session                *Session //注入的隔离字段
	isCommitedOrRollbacked bool     //
}

func (database *DataBase) Begin() error {
	database.newSession()
	return database.session.Begin()
}

func (database *DataBase) newSession() *Session {
	//初始化session（此时没有tableMode、injectionMp）
	if database.session == nil {
		database.session = NewSession(database.engine)
	}
	//非事务时，副本session进行了close，此时条件满足，进入。。。
	//事务操作时，副本session并没有进行close，此时条件不满足
	if database.session.IsClosed() {
		database.session = nil
		return database.newSession()
	}
	//克隆一个相同的session
	//_session := database.session.Clone()
	return database.session.Clone()
}

func (database *DataBase) NewMode(tableMode interface{}, injectionMp ...utils.Mp) Mode {
	return *newMode(database, tableMode, injectionMp...)
}

func (database *DataBase) GetCommitOrRollback() bool {
	if database.session != nil {
		return database.session.GetCommitOrRollback()
	}
	return true
}

func (database *DataBase) Rollback() error {
	if database.session != nil {
		return database.session.Rollback()
	}
	return nil
}

func (database *DataBase) Commit() error {
	if database.session != nil {
		return database.session.Commit()
	}
	return nil
}

func (database *DataBase) Close(force ...bool) *DataBase {
	if database.session != nil {
		database.session.Close(force...)
		if database.session.IsClosed() {
			database.session = nil
		}
	}
	return database
}

func (database *DataBase) GetSession() *Session {
	return database.session
}
