package apigen

import "git.qianqiusoft.com/qianqiusoft/light-apiengine-client/code_gen/utils"

const modelTemplate = `
package models
import (
	{{if ParamsContainDT .data.ColumnList}}sysmodel "git.qianqiusoft.com/qianqiusoft/light-apiengine/models"{{- end}}
	//__import_packages__
)
{{$structName := CamelizeStr .data.Name true}}
//{{.data.Desc}}
type {{$structName}} struct {

    {{range .data.ColumnList -}}
	//{{.Caption}}
	{{CamelizeStr .Name true}}   {{XormTime .Type}}   {{Backquote}}{{Xorm . | Unescaped}}json:"{{.Name}}"{{Backquote}}
    {{end}}
}

func (t *{{$structName}}) TableName() string {
	return "{{.data.Name}}"
}

func init() {
	AddTableName("{{.data.Name}}")
	RegisterModel(new({{$structName}}))
}
`

func GenModel(templateData interface{}, params map[string]interface{}) ([]byte, error) {
	return utils.GenTemplate(modelTemplate, templateData, params)
}

func GenModelGo(templateData interface{}, params map[string]interface{}) ([]byte, error) {
	out := utils.Str2bytes(ModelGo)
	return out, nil
}

const ModelGo = `
package models

import (
	"fmt"
	"git.qianqiusoft.com/qianqiusoft/light-apiengine/config"
	"github.com/xormplus/xorm"
	"sync"
)

var beans []interface{}
var ModelNameList []string
var beansLock sync.Mutex

func RegisterModel(models ...interface{}) {
	beansLock.Lock()
	defer beansLock.Unlock()

	for _, model := range models {
		beans = append(beans, model)
	}
}

func AddTableName(tableName string) {
	beansLock.Lock()
	defer beansLock.Unlock()

	ModelNameList = append(ModelNameList, tableName)
}

func SyncDb(db *xorm.Engine) {
	if !config.AppConfig.SyncDb {
		return
	}
	err := db.Sync2(beans...)
	if err != nil {
		fmt.Println(err)
	}
}
`
