package utils

import (
	"github.com/go-xorm/xorm"
)

// Context 上下文
// 只限制在每次 Request 内
type Context struct {
	DB  *xorm.Session
	box map[string]interface{}
}

// NewContext 初始化上下文
func NewContext(engine *xorm.Engine, opt map[string]interface{}) *Context {
	return &Context{
		DB:  engine.NewSession(),
		box: opt,
	}
}

// Get 获取
func (c *Context) Get(key string, def ...interface{}) interface{} {
	if c.box != nil {
		if opt, has := c.box[key]; has {
			return opt
		}
	}

	if len(def) > 0 {
		return def[0]
	}

	return nil
}

// Set 设置
func (c *Context) Set(key string, val interface{}) {
	if c.box == nil {
		c.box = make(map[string]interface{})
	}

	c.box[key] = val
}

// Ready Request 级别初始化
func (c *Context) Ready() error {
	// 开启事务
	if err := c.DB.Begin(); err != nil {
		return err
	}

	return nil
}

// Destroy 析构函数
func (c *Context) Destroy() {
	c.DB.Close()
}