package web

//go:generate ./build.sh

import (
	"net/http"

	log "github.com/Sirupsen/logrus"
	assetfs "github.com/elazarl/go-bindata-assetfs"
	goji "goji.io"
	"goji.io/pat"
)

var (
	assetFS = &assetfs.AssetFS{
		Asset:     Asset,
		AssetDir:  AssetDir,
		AssetInfo: AssetInfo,
		Prefix:    "",
	}

	indexHTMLAliases = []string{
		"metrics",
		"metrics/*",
		"orgs",
		"orgs/*",
		"projects",
		"projects/*",
		"teams",
		"teams/*",
		"settings",
		"help",
		"enroll",
	}
)

// NewMux returns an HTTP request multiplexer configured for our handlers.
func NewMux() http.Handler {
	// Using twitchhttp to give us a standard health check and rollbar support.
	mux := goji.SubMux()

	for _, alias := range indexHTMLAliases {
		mux.HandleFunc(pat.Get("/"+alias), indexHTMLHandler)
	}
	mux.Handle(pat.Get("/*"), http.FileServer(assetFS))

	return mux
}

func indexHTMLHandler(w http.ResponseWriter, r *http.Request) {
	f, err := assetFS.Open("index.html")
	if err != nil {
		log.Fatalf("Couldn't get index.html asset: %v", err)
	}
	stat, err := f.Stat()
	if err != nil {
		log.Fatalf("Couldn't get index.html asset: %v", err)
	}
	http.ServeContent(w, r, stat.Name(), stat.ModTime(), f)
}
