package main

import (
	"context"
	"log"
	"net/http"
	"time"

	"srs.epita.fr/fic-server/qa/api"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/memstore"
	"github.com/gin-gonic/gin"
)

type App struct {
	router *gin.Engine
	srv    *http.Server
}

func NewApp(baseURL string) App {
	gin.ForceConsoleColor()
	router := gin.Default()

	store := memstore.NewStore([]byte("secret"))
	router.Use(sessions.Sessions("qa-session", store))

	api.DeclareRoutes(router.Group(""))

	var baserouter *gin.RouterGroup
	if len(baseURL) > 0 {
		router.GET("/", func(c *gin.Context) {
			c.Redirect(http.StatusFound, baseURL)
		})

		baserouter = router.Group(baseURL)

		api.DeclareRoutes(baserouter)
		declareStaticRoutes(baserouter, baseURL)
	} else {
		declareStaticRoutes(router.Group(""), "")
	}

	app := App{
		router: router,
	}

	return app
}

func (app *App) Start(bind string) {
	app.srv = &http.Server{
		Addr:              bind,
		Handler:           app.router,
		ReadHeaderTimeout: 15 * time.Second,
		ReadTimeout:       15 * time.Second,
		WriteTimeout:      10 * time.Second,
		IdleTimeout:       30 * time.Second,
	}

	if err := app.srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		log.Fatalf("listen: %s\n", err)
	}
}

func (app *App) Stop() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := app.srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
}
