package main

import (
	"encoding/base64"
	"gdsm/models/ec"
	"gdsm/models/userMgr"
	_ "gdsm/routers"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/plugins/cors"
	_ "github.com/mattn/go-sqlite3"
	"strings"
	"wb/cc"
	"wb/cfg"
	"wb/ii"
	"wb/lg"
	"wb/modbus"
)

func initLog() {
	dataPath := cfg.WbConfig.DataPath
	if beego.BConfig.RunMode == "prod" {
		lg.InitLog(lg.LevelInfo, dataPath+"/log")
	} else {
		lg.InitLog(lg.LevelDebug, dataPath+"/log")
	}
}
func initDb() {
	orm.RegisterDriver("sqlite", orm.DRSqlite)
	dbPath := cfg.WbConfig.DataPath + "/db/main.db"
	lg.Info("initDb file:", dbPath)
	orm.RegisterDataBase("default", "sqlite3", dbPath)
	orm.Debug = true
}

var filterUser = func(ctx *context.Context) {
	switch ctx.Input.URL() {
	case "/login", "/logout":
		return
	}
	ctx.Input.CruSession.Set(ec.SessionDepartment, "1")
	ctx.Input.CruSession.Set(cc.SessionUser, userMgr.User{"2019022114365001", "1", "1", "role_user", "1", ""})
	usr := ctx.Input.Session(cc.SessionUser)
	if usr == nil && ctx.Request.RequestURI != "/login" {
		lg.Debug("FilterUser need login: ", ctx.Input.URL(), ctx.Input.URI())
		if strings.EqualFold("POST", ctx.Request.Method) {
			ctx.WriteString("need_login")
			return
		}
		redirect := ctx.Input.URI()
		redirectB64 := base64.URLEncoding.EncodeToString([]byte(redirect))
		ctx.Redirect(302, "/login?redirect="+redirectB64)
	}
}

func main() {
	cfg.InitConfig()
	initLog()
	initDb()
	ii.LoadItemInfo("conf/item/fields")
	modbus.LoadModelInfo("conf/mdbs")
	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
	}))
	//beego.InsertFilter("/*", beego.BeforeRouter, filterUser)
	beego.Run()
}
