package main

import (
	"html/template"
	"net/http"
	"os"
	"path"
	"strings"
	"time"
)

func serveTemplate(w http.ResponseWriter, r *http.Request) {
	logit("Called URL: " + r.URL.Path)
	// wennn kein File angegeben ist: index.html
	if r.URL.Path == "/" {
		r.URL.Path = "/index.html"
	}
	lp := path.Join("templates", "layout.html")
	fp := path.Join("snippets", r.URL.Path)

	// Return a 404 if the template doesn't exist
	_, err := os.Stat(fp)
	if err != nil {
		if os.IsNotExist(err) {
			logit("URL not found: " + fp)
			fp = path.Join("snippets", "404.html")
		}
	}

	tmpl, err := template.ParseFiles(lp, fp)
	if err != nil {
		// Log the detailed error
		logit(err.Error())
		// Return a generic "Internal Server Error" message
		http.Error(w, http.StatusText(500), 500)
		return
	}

	var userName = getUserName(r)

	t := time.Now()
	var datetimestring = t.Format("20060102150405")
	var trackers = getMyDevs(userName)
	var last_metrics []OneMetric

	query_values := r.URL.Query()

	if r.URL.Path == "/tracker.html" {
		// wir holen noch die letzten Metriken
		for _, v := range trackers {
			deveui := v
			readonly := false
			if strings.HasPrefix(deveui, "@") {
				deveui = deveui[1:]
				readonly = true
			}
			last_metric := getLastMetrics(deveui)
			last_metric.Readonly = readonly
			last_metrics = append(last_metrics, last_metric)
		}
	}

	data := struct {
		UserName       string
		DateTimeString string
		Tracker        []string
		LastMetrics    []OneMetric
		QueryValues    map[string][]string
	}{
		userName,
		datetimestring,
		trackers,
		last_metrics,
		query_values,
	}

	if err := tmpl.ExecuteTemplate(w, "layout", &data); err != nil {
		logit(err.Error())
		http.Error(w, http.StatusText(500), 500)
	}
}

func main() {
	initDB()
	defer closeDB()
	fs := http.FileServer(http.Dir("static"))
	http.Handle("/static/", http.StripPrefix("/static/", fs))
	http.Handle("/favicon.ico", fs)
	http.HandleFunc("/", serveTemplate)

	http.HandleFunc("/login", loginHandler)
	http.HandleFunc("/reset_password", resetPasswordHandler)
	http.HandleFunc("/set_password", setPasswordHandler)
	http.HandleFunc("/logout", logoutHandler)
	http.HandleFunc("/confirm", confirmHandler)
	http.HandleFunc("/metrics", metricsHandler)
	http.HandleFunc("/save_tracker_settings", save_tracker_settingsHandler)
	http.HandleFunc("/getstripepaymentintent", getstripepaymentintentHandler)
	http.HandleFunc("/stripewebhook", stripeWebhookHandler)

	logit("Starting Web Application...")
	http.ListenAndServe("127.0.0.1:4000", nil)
	logit("Terminating Web Application...")
}
