package apigen

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

const routerTemplate = `
package routers

import (
	"git.qianqiusoft.com/qianqiusoft/light-apiengine/engine"
	"git.qianqiusoft.com/qianqiusoft/light-apiengine/middleware"
	"{{.app.ApplicationName}}/controllers/gen"
)

func init(){
	addRegisterHandler(register{{CamelizeStr .data.Name true}}Router)
}

func register{{CamelizeStr .data.Name true}}Router(e *engine.ApiEngine){
	api:=e.GinEngine.Group("/api")
	v1:=api.Group("/v1/{{.data.Name}}")
	v1.Use(middleware.LoginWare())
	if len(_router["{{.data.Name}}"]) >0 {
		v1.Use(_router["{{.data.Name}}"]...)
	}
	ctrler := gen.New{{CamelizeStr .data.Name true}}Controller(e)


{{range .data.Apis}}
	{{if not (Contains .Method "get")}}//{{end}}v1.GET("/{{.Name}}",ctrler.{{CamelizeStr .Name true}})
	{{if not (Contains .Method "post")}}//{{end}}v1.POST("/{{.Name}}",ctrler.{{CamelizeStr .Name true}})
{{end}}
}
`

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

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

const RouterGenGo = `
package routers

import (
	"git.qianqiusoft.com/qianqiusoft/light-apiengine/engine"
    "git.qianqiusoft.com/qianqiusoft/light-apiengine/entitys"
	"github.com/gin-gonic/gin"
	"{{.app.ApplicationName}}/models"
	"sync"
)

var (
	_registerHandlers []func(e *engine.ApiEngine) = nil
	_registerHandlerMutex sync.Mutex
    _router       map[string][]gin.HandlerFunc
)

func addRegisterHandler(handler func(e *engine.ApiEngine)){
	_registerHandlerMutex.Lock()
	defer _registerHandlerMutex.Unlock()
	if _registerHandlers == nil{
		_registerHandlers = make([]func(e *engine.ApiEngine), 0)
	}
	_registerHandlers = append(_registerHandlers, handler)
}

func UseMiddleware(name string, middle ...gin.HandlerFunc) {
	if _router == nil {
		_router = make(map[string][]gin.HandlerFunc)
	}
	_router[name] =  append(_router[name], middle...)
}

func Register(e *engine.ApiEngine){
    e.AddAppMoudleInitFunc("{{.app.ApplicationName}}", DbInitFunc)
	_registerHandlerMutex.Lock()
	defer _registerHandlerMutex.Unlock()
	for i := range _registerHandlers{
		_registerHandlers[i](e)
	}
}

func DbInitFunc(domain string, e entitys.ApiEngineInterface)  {
	if domain == ""{
		for _,db := range e.GetAllBusinessDb() {
			models.SyncDb(db)
		}
	}else {
		db := e.GetBusinessDb(domain)
		models.SyncDb(db)
	}
}

`
