package api

import (
	"git.sp4ke.com/sp4ke/bit4sat/config"
	"github.com/boj/redistore"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

var (
	upCtrl = UploadCtrl{}
)

type API struct {
	router *gin.Engine
}

func (api *API) Run() {

	// Get last session if it exists

	v1 := api.router.Group("/api/v1")
	v1.GET("/session", upSessionHandler)

	uploadRoute := v1.Group("/u")
	{
		uploadRoute.POST("", upCtrl.New)
		uploadRoute.PUT("/:id", upCtrl.Upload)
		//TODO: make a poll version + this one
		uploadRoute.GET("/check/:id", upCtrl.CheckStatus)
		uploadRoute.GET("/poll/:id", upCtrl.PollStatus)
	}

	// Invoice poller
	// invoice id is the RHash field
	v1.GET("/pollinvoice/:rhash", pollInvoice)

	// Download route
	downRoute := v1.Group("/d")
	{

		// Query download
		downRoute.GET("/q/:dlId", download)

		// Get file
		downRoute.GET("/g/:dlKey", getFiles)
	}

	adminRoute := v1.Group("/a")
	{
		adminRoute.GET("/info/:adminToken", adminGetInfo)
	}

	// test rout
	v1.GET("/t", TestDownHandler)

	// Websocket server
	//api.router.GET("/ws", ws.Serve)

	// LN charge callback
	//api.router.POST("/"+config.ChargeCallbackEndpoint, invoiceCbHandler)

	api.router.Run(config.ApiListen)
}

func NewAPI() *API {
	router := gin.Default()
	router.Use(cors.Default())

	// Setup Session
	var err error
	SessionStore, err = redistore.NewRediStore(10, "tcp", "redis:6379",
		"", []byte(config.SessionSecret))
	if err != nil {
		panic(err)
	}

	//
	//
	//router.Use(secure.New(secure.Config{
	//ContentSecurityPolicy: "default-src 'self'; script-src *; worker-src *",
	////IsDevelopment: true,
	//}))

	return &API{
		router: router,
	}
}
