package main

import (
	"fmt"
	"sparrow/pkg/generator"
	"sparrow/pkg/server"
	"sparrow/services/knowoapi/model"

	"github.com/iris-contrib/middleware/cors"
	"github.com/kataras/iris"
)

func main() {

	err := server.Init("knowoapi")
	if err != nil {
		server.Log.Fatal(err)
		return
	}
	app := newApp()
	// register a http handler
	err = server.RegisterHTTPHandler(app)
	if err != nil {
		server.Log.Errorf("RegisterHTTPHandler Error: %s", err)
		return
	}
	// go
	err = server.Run()
	if err != nil {
		server.Log.Fatal(err)
	}
}

func newApp() *iris.Application {
	app := iris.New()
	//cors
	opts := cors.Options{
		AllowedOrigins: []string{"*"},
		AllowedHeaders: []string{"Content-Type", "Authorization"},
		AllowedMethods: []string{"POST", "GET", "DELETE", "PUT"},
		ExposedHeaders: []string{"X-Header"},
		//Debug:          true,
	}
	app.Use(cors.New(opts))
	app.AllowMethods(iris.MethodOptions)
	registerErrors(app)
	db, err := getDB()
	if err != nil {
		fmt.Print(err)
	}
	models := new(model.All).Init(db)
	gen, err := generator.NewKeyGenerator(*confAESKey)
	if err != nil {
		fmt.Print(err)
	}

	//注册路由
	registerRouters(app, models, gen)
	app.Build()
	return app
}
