package webserver

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

	"git.tovijaeschke.xyz/tovi/personal_website/variables"
	"github.com/gorilla/mux"
)

var (
	WebRoot string
)

func init() {
	WebRoot = filepath.Join(
		variables.ProjectRoot,
		"/web",
	)
}

func webRootJoin(p string) string {
	return filepath.Join(
		WebRoot,
		p,
	)
}

func Start() error {
	var (
		r *mux.Router
		e error
	)

	r = mux.NewRouter()

	// For images / anything static
	r.PathPrefix("/static/").Handler(
		http.StripPrefix("/static/",
			http.FileServer(http.Dir(webRootJoin("static"))),
		),
	)

	// Handle CSS
	r.PathPrefix("/css/").Handler(
		http.StripPrefix("/css/",
			http.FileServer(http.Dir(webRootJoin("css"))),
		),
	)

	// Handle JS
	r.PathPrefix("/js/").Handler(
		http.StripPrefix("/js/",
			http.FileServer(http.Dir(webRootJoin("js"))),
		),
	)

	// Public endpoints
	r.HandleFunc("/", ViewIndex)
	r.HandleFunc("/links", ViewLinks)
	r.HandleFunc("/programming", ViewPostListProgramming)
	r.HandleFunc("/pentesting", ViewPostListPentesting)
	r.HandleFunc("/post/{id}", ViewPost)
	r.HandleFunc("/error", ViewError)

	// Administration
	r.HandleFunc("/admin", AdminView)
	r.HandleFunc("/admin/login", AdminLogin)
	r.HandleFunc("/admin/logout", AdminLogout)
	r.HandleFunc("/admin/post/new", AdminNewPost)
	r.HandleFunc("/admin/post/{id}/edit", AdminEditPost)

	e = http.ListenAndServe(variables.WebserverHost, r)
	if e != nil {
		return e
	}

	return nil
}
