package dashboard

import (
	"net/http"
	"path/filepath"
	"strings"

	"github.com/gobuffalo/packr/v2"
	"k8s.io/klog/v2"
)

var assetBox = (*packr.Box)(nil)

// getAssetBox returns a binary-friendly set of assets packaged from disk
func getAssetBox() *packr.Box {
	if assetBox == (*packr.Box)(nil) {
		assetBox = packr.New("Assets", "assets")
	}
	return assetBox
}

// Asset replies with the contents of the loaded asset from disk
func Asset(assetPath string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		asset, err := getAssetBox().Find(assetPath)
		if err != nil {
			klog.Errorf("Error getting asset: %v", err)
			http.Error(w, "Error getting asset", http.StatusInternalServerError)
			return
		}

		// Set content type based on file extension
		ext := strings.ToLower(filepath.Ext(assetPath))
		switch ext {
		case ".css":
			w.Header().Set("Content-Type", "text/css; charset=utf-8")
		case ".js":
			w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
		case ".svg":
			w.Header().Set("Content-Type", "image/svg+xml")
		case ".png":
			w.Header().Set("Content-Type", "image/png")
		case ".jpg", ".jpeg":
			w.Header().Set("Content-Type", "image/jpeg")
		case ".ico":
			w.Header().Set("Content-Type", "image/x-icon")
		}

		_, err = w.Write(asset)
		if err != nil {
			klog.Errorf("Error writing asset: %v", err)
		}
	})
}

// StaticAssets replies with a FileServer for all assets
func StaticAssets(prefix string) http.Handler {
	box := getAssetBox()
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path := strings.TrimPrefix(r.URL.Path, prefix)

		// Set content type based on file extension
		ext := strings.ToLower(filepath.Ext(path))
		switch ext {
		case ".css":
			w.Header().Set("Content-Type", "text/css; charset=utf-8")
		case ".js":
			w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
		case ".svg":
			w.Header().Set("Content-Type", "image/svg+xml")
		case ".png":
			w.Header().Set("Content-Type", "image/png")
		case ".jpg", ".jpeg":
			w.Header().Set("Content-Type", "image/jpeg")
		case ".ico":
			w.Header().Set("Content-Type", "image/x-icon")
		}

		http.FileServer(box).ServeHTTP(w, r)
	})
}
