package main

import (
	"net/http"
	"sparrow/pkg/mysql"
	"sparrow/pkg/server"

	"github.com/go-martini/martini"
	"github.com/jinzhu/gorm"
	"github.com/martini-contrib/render"
	"github.com/xyproto/permissionsql"
)

func main() {
	// init server
	err := server.Init("apiprovidor")
	if err != nil {
		server.Log.Fatal(err)
		return
	}
	DSN := *confDBUser + ":" + *confDBPass + "@tcp(" + *confDBHost + ":" + *confDBPort + ")/" + *confDBName + "?charset=utf8&parseTime=True"
	// martini setup

	martini.Env = martini.Prod
	handler := martini.Classic()
	perm, err := permissionsql.NewWithDSN(DSN, *confDBName)
	if err != nil {
		server.Log.Fatal(err)
		return
	}
	handler.Use(render.Renderer())
	permissionHandler := func(w http.ResponseWriter, req *http.Request, c martini.Context) {
		// Check if the user has the right admin/user rights
		if perm.Rejected(w, req) {
			// Deny the request
			http.Error(w, "Permission denied!", http.StatusForbidden)
			// Reject the request by not calling the next handler below
			return
		}
		// Call the next middleware handler
		c.Next()
	}
	handler.Use(permissionHandler)
	route(handler, perm)

	// register a http handler
	err = server.RegisterHTTPHandler(handler)
	if err != nil {
		server.Log.Errorf("RegisterHTTPHandler Error: %s", err)
		return
	}

	// run notifier
	// err = RunNotifier()
	// if err != nil {
	// 	server.Log.Fatalf("Run Notifier Error: %s", err)
	// }

	// go
	err = server.Run()
	if err != nil {
		server.Log.Fatal(err)
	}
}

func getDB() (*gorm.DB, error) {
	db, err := mysql.GetClient(*confDBHost, *confDBPort, *confDBName, *confDBUser, *confDBPass)
	if err != nil {
		return nil, err
	}
	gormdb, err := gorm.Open("mysql", db)
	if err != nil {
		return nil, err
	}
	gormdb.SingularTable(true)
	gormdb.LogMode(true)
	return gormdb, nil
}
