package main

import (
	"bytes"
	"embed"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"path"
	"strings"
	"time"

	"srs.epita.fr/fic-server/libfic"
	"srs.epita.fr/fic-server/settings"

	"github.com/gin-gonic/gin"
)

//go:embed static

var assets embed.FS
var staticFS http.FileSystem

var forwarder *string = nil
var fwdPublicJson = false

var indexTmpl []byte

func getIndexHtml(w io.Writer, baseURL string) {
	if len(indexTmpl) == 0 {
		if file, err := staticFS.Open("index.html"); err != nil {
			log.Println("Unable to open index.html: ", err)
		} else {
			defer file.Close()

			if indexTmpl, err = ioutil.ReadAll(file); err != nil {
				log.Println("Cannot read whole index.html: ", err)
			} else {
				indexTmpl = bytes.Replace(indexTmpl, []byte("{{.urlbase}}"), []byte(path.Clean(path.Join(baseURL+"/", "nuke"))[:len(path.Clean(path.Join(baseURL+"/", "nuke")))-4]), -1)
			}
		}
	}

	w.Write(indexTmpl)
}

func serveFile(c *gin.Context, url string) {
	c.Request.URL.Path = url
	http.FileServer(staticFS).ServeHTTP(c.Writer, c.Request)
}

func declareStaticRoutes(router *gin.RouterGroup, baseURL string) {
	router.GET("/", func(c *gin.Context) {
		http.Redirect(c.Writer, c.Request, "public0.html", http.StatusFound)
	})
	for i := 0; i <= 9; i++ {
		router.GET(fmt.Sprintf("/public%d.html", i), func(c *gin.Context) {
			getIndexHtml(c.Writer, baseURL)
		})
	}

	router.GET("/css/*_", func(c *gin.Context) {
		serveFile(c, strings.TrimPrefix(c.Request.URL.Path, baseURL))
	})
	router.GET("/fonts/*_", func(c *gin.Context) {
		serveFile(c, strings.TrimPrefix(c.Request.URL.Path, baseURL))
	})
	router.GET("/img/*_", func(c *gin.Context) {
		serveFile(c, strings.TrimPrefix(c.Request.URL.Path, baseURL))
	})
	router.GET("/js/*_", func(c *gin.Context) {
		serveFile(c, strings.TrimPrefix(c.Request.URL.Path, baseURL))
	})
	router.GET("/views/*_", func(c *gin.Context) {
		serveFile(c, strings.TrimPrefix(c.Request.URL.Path, baseURL))
	})

	router.GET("/files/*_", func(c *gin.Context) {
		if forwarder != nil {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(fic.FilesDir, strings.TrimPrefix(c.Request.URL.Path, "/"+path.Join(baseURL, "files"))))
		}
	})

	router.GET("/events.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(TeamsDir, "events.json"))
		}
	})
	router.GET("/my.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(TeamsDir, "public", "my.json"))
		}
	})
	router.GET("/api/teams/:tid/score-grid.json", func(c *gin.Context) {
		if forwarder != nil {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			fwd_request(c.Writer, c.Request, "http://127.0.0.1:8081/")
		}
	})
	router.GET("/api/teams/:tid/stats.json", func(c *gin.Context) {
		if forwarder != nil {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			fwd_request(c.Writer, c.Request, "http://127.0.0.1:8081/")
		}
	})
	router.GET("/challenge.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(settings.SettingsDir, settings.ChallengeFile))
		}
	})
	router.GET("/settings.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			c.Writer.Header().Set("X-FIC-Time", fmt.Sprintf("%f", float64(time.Now().UnixNano()/1000)/1000000))
			http.ServeFile(c.Writer, c.Request, path.Join(settings.SettingsDir, settings.SettingsFile))
		}
	})
	router.GET("/teams.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(TeamsDir, "public", "teams.json"))
		}
	})
	router.GET("/themes.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(TeamsDir, "themes.json"))
		}
	})

	router.GET("/background.png", func(c *gin.Context) {
		if forwarder != nil && fwdPublicJson {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(DashboardDir, "background.png"))
		}
	})

	router.GET("/public.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil && fwdPublicJson {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(DashboardDir, "public.json"))
		}
	})
	router.GET("/public0.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil && fwdPublicJson {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(DashboardDir, "public0.json"))
		}
	})
	router.GET("/public1.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil && fwdPublicJson {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(DashboardDir, "public1.json"))
		}
	})
	router.GET("/public2.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil && fwdPublicJson {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(DashboardDir, "public2.json"))
		}
	})
	router.GET("/public3.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil && fwdPublicJson {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(DashboardDir, "public3.json"))
		}
	})
	router.GET("/public4.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil && fwdPublicJson {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(DashboardDir, "public4.json"))
		}
	})
	router.GET("/public5.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil && fwdPublicJson {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(DashboardDir, "public5.json"))
		}
	})
	router.GET("/public6.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil && fwdPublicJson {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(DashboardDir, "public6.json"))
		}
	})
	router.GET("/public7.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil && fwdPublicJson {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(DashboardDir, "public7.json"))
		}
	})
	router.GET("/public8.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil && fwdPublicJson {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(DashboardDir, "public8.json"))
		}
	})
	router.GET("/public9.json", func(c *gin.Context) {
		c.Writer.Header().Set("Cache-Control", "no-cache")
		if forwarder != nil && fwdPublicJson {
			fwd_request(c.Writer, c.Request, *forwarder)
		} else {
			http.ServeFile(c.Writer, c.Request, path.Join(DashboardDir, "public9.json"))
		}
	})
}
