package serve

import (
	"context"
	"net/http"
	"path"
	"strconv"
	"time"

	"github.com/fvbock/endless"
	"github.com/gin-contrib/static"
	"github.com/gin-gonic/gin"
	"github.com/shroff/phylum/server/internal/api/publink"
	apiv1 "github.com/shroff/phylum/server/internal/api/v1"
	"github.com/shroff/phylum/server/internal/api/webdav"
	"github.com/shroff/phylum/server/internal/core/fs"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
)

const trashRetainDuration = 30 * 24 * time.Hour

var Cfg Config

func SetupCommand() *cobra.Command {
	var cmd = &cobra.Command{
		Use:     "serve",
		Short:   "Run the server",
		GroupID: "server",
	}

	flags := cmd.Flags()

	flags.Bool("db_trace", false, "Trace Database Queries")
	flags.MarkHidden("db_trace")

	flags.String("server_host", "", "Server Host")
	flags.String("server_port", "", "Server Port")
	flags.String("server_webappsrc", "", "Web App Source Directory")
	flags.String("server_publinkpath", "", "Public Share path prefix")
	flags.String("server_webdavpath", "", "WebDAV path prefix")
	flags.Bool("server_cors_enabled", false, "Enable CORS")
	flags.StringSlice("server_cors_origins", nil, "CORS origins")
	flags.Bool("server_logbody", false, "Log Response Body (Must be used with --debug)")

	cmd.Run = func(cmd *cobra.Command, args []string) {
		if !Cfg.Debug {
			gin.SetMode(gin.ReleaseMode)
		}
		engine := createEngine()

		webdav.SetupHandler(engine.Group(Cfg.WebDAVPath))
		apiv1.Setup(engine.Group("/api/v1"))
		publink.Setup(engine.Group(Cfg.PublinkPath))

		if Cfg.WebAppSrc != "" {
			setupWebApp(engine, Cfg.WebAppSrc)
		}
		setupTrashCompactor()

		listen := Cfg.Host + ":" + strconv.Itoa(Cfg.Port)
		server := endless.NewServer(listen, engine)
		server.BeforeBegin = func(addr string) {
			logrus.Info("Listening on " + addr)
		}

		if err := server.ListenAndServe(); err != nil {
			logrus.Fatal(err.Error())
		}
	}

	return cmd
}

func setupWebApp(r gin.IRoutes, webAppSrcDir string) {
	fs := static.LocalFile(webAppSrcDir, false)
	fileserver := http.FileServer(fs)
	indexFilePath := path.Join(webAppSrcDir, "index.html")

	staticFileHandler := func(c *gin.Context) {
		if c.Request.Method == "GET" {
			c.Writer.Header().Set("Cross-Origin-Embedder-Policy", "credentialless")
			c.Writer.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
			if fs.Exists("/", c.Request.URL.Path) {
				fileserver.ServeHTTP(c.Writer, c.Request)
			} else {
				http.ServeFile(c.Writer, c.Request, indexFilePath)
			}
		} else {
			c.JSON(http.StatusNotFound, gin.H{
				"status": 404,
				"code":   "route_not_found",
				"msg":    "Route Not Found",
			})
		}
	}
	r.Use(staticFileHandler)
}

func setupTrashCompactor() {
	ticker := time.NewTimer(24 * time.Hour)
	go func() {
		for {
			<-ticker.C
			fs.TrashCompact(context.Background(), trashRetainDuration)
		}
	}()
	fs.TrashCompact(context.Background(), trashRetainDuration)
}
