package web

import (
	"fmt"
	"log"
	"net/http/httputil"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/spf13/viper"
)

var proxies = make(map[string]*httputil.ReverseProxy)

func Run() error {
	router := setupRouter()
	address := fmt.Sprintf("%s:%d", viper.GetString("ip_addr"), viper.GetInt("port"))
	log.Println("Listening on address", address)
	var err error
	if viper.GetBool("ssl") == true {
		err = router.RunTLS(
			address,
			viper.GetString("ssl_cert"),
			viper.GetString("ssl_cert_key"),
		)
		log.Println("Using SSL")
	} else {
		err = router.Run(address)
	}
	log.Println("Router is ready")
	if err != nil {
		log.Panic("Could not start Webserver: ", err)
		return err
	}
	return nil
}

func setupRouter() *gin.Engine {
	log.Println("Setting up router")
	gin.ForceConsoleColor()
	gin.SetMode("release")
	router := gin.New()
	store := cookie.NewStore([]byte(uuid.NewString()))
	store.Options(sessions.Options{
		MaxAge: viper.GetInt("maxAge"),
	})
	router.Use(gin.Recovery())
	router.Use(sessions.Sessions("session", store))
	//router.Use(urlLog())
	if viper.GetBool("block_filebrowser") == true {
		router.Use(blockFilebrowser)
	}
	router.Use(containerProxy)
	// router.Any("/", containerProxy)
	return router
}

func urlLog() gin.HandlerFunc {
	return func(c *gin.Context) {

		log.Printf(
			"[INFO] %s: %s: %s",
			c.Request.RemoteAddr,
			c.Request.Method,
			c.Request.URL,
		)
	}
}

// blockFilebrowser blocks the URLs used by the Kclient File browser
func blockFilebrowser(c *gin.Context) {
	switch c.Request.URL.RawPath {
	case "/files":
		c.Abort()
	case "/filebrowser.js":
		c.Abort()
	case "/files/socket.io":
		c.Abort()

	default:
		c.Next()
	}
}
