package webcontroller

import (
	"net/http"
	"os"

	"fornaxian.tech/log"
	"github.com/julienschmidt/httprouter"
)

// New initializes a new WebController by registering all the request handlers
// and parsing all templates in the resource directory
func serveSK(r *httprouter.Router) (err error) {
	// r.ServeFiles("/_app/*filepath", http.Dir(assetsPath+"/_app"))
	// r.ServeFiles("/style/*filepath", http.Dir(assetsPath+"/style"))

	readdir, err := os.ReadDir(assetsPath)
	if err != nil {
		return err
	}
	for _, entry := range readdir {
		if entry.Type().IsRegular() {
			serveFile(r, "/"+entry.Name(), assetsPath+"/"+entry.Name())
		} else if entry.IsDir() {
			r.ServeFiles("/"+entry.Name()+"/*filepath", http.Dir(assetsPath+"/"+entry.Name()))
		}
	}

	r.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Debug("Running fallback handler for %s", r.URL.Path)
		http.ServeFile(w, r, assetsPath+"/fallback.html")
	})
	return nil
}

const assetsPath = "/home/wim/Workspace/svelte/fnx_sk/build"

func serveFile(r *httprouter.Router, path, file string) {
	var handler = func(
		w http.ResponseWriter,
		r *http.Request,
		p httprouter.Params,
	) {
		http.ServeFile(w, r, assetsPath+"/"+file)
	}

	r.GET(path, handler)
	r.HEAD(path, handler)
	r.OPTIONS(path, handler)
	r.POST(path, handler)
	r.PUT(path, handler)
	r.PATCH(path, handler)
	r.DELETE(path, handler)
}
