package jccommon

import (
	"q5"
	"f5"
)

func AddDbLog(dataSource string, logType string, subType string,
	params map[string]string) error {
	params["type"] = logType
	params["subtype"] = subType
	nowTime := f5.GetApp().GetRealSeconds()
	if _, ok := params["createtime"]; !ok {
		params["createtime"] = q5.ToString(nowTime)
	}
	if _, ok := params["modifytime"]; !ok {
		params["modifytime"] = q5.ToString(nowTime)
	}
	var resultErr error
	f5.GetGoStyleDb().Insert(
		dataSource,
		"t_log",
		[][]string{},
		func (err error, lastInsertId int64, rowsAffected int64) {
			resultErr = err
		})
	return resultErr
}

func GetDbParam(dataSource string, name string) (string, error) {
	var resultErr error
	var val string
	f5.GetGoStyleDb().OrmSelectOne(
		dataSource,
		"t_param",
		[][]string{
			{"name", name},
		},
		func (err error, ds *f5.DataSet) {
			resultErr = err
			if err != nil {
				return
			}
			if ds.Next() {
				val = ds.GetByName("val")
			}
		})
	return val, resultErr
}

func SaveDbParam(dataSource string, name string, val string) error {
	var resultErr error
	nowTime := f5.GetApp().GetRealSeconds()
	f5.GetGoStyleDb().Upsert(
		dataSource,
		"t_param",
		[][]string{
			{"name", name},
		},
		[][]string{
			{"val", val},
			{"modifytime", q5.ToString(nowTime)},
		},
		[][]string{
			{"name", name},
			{"val", val},
			{"createtime", q5.ToString(nowTime)},
			{"modifytime", q5.ToString(nowTime)},
		},
		func (err error, lastInsertId int64, rowsAffected int64) {
			resultErr = err
		})
	return resultErr
}
