package main

import (
	"html/template"
	"log"
	"net/http"
	"os"

	"192.168.1.180/odonax/filehost-athome/config"
	"192.168.1.180/odonax/filehost-athome/database"
	"192.168.1.180/odonax/filehost-athome/handlers"
)

func main() {
	cfgPath := "config.toml"
	cfg := config.Load(cfgPath)

	handlers.Cfg = &cfg
	handlers.CfgPath = cfgPath

	os.MkdirAll(cfg.DataDir+"/files", 0755)

	db := database.Open(cfg.DataDir+"/hub.db")
	defer db.Close()

	tmpl := template.Must(template.ParseGlob("templates/*.html"))

	// tmpl, err := template.ParseFiles("templates/home.html")
	// if err != nil {
	// 	log.Fatal("Failed to load template:", err)
	// }

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		data := map[string]string{
			"Name":        cfg.SiteName,
			"Description": "This is where you'll own your files and share them freely.",
		}
		tmpl.ExecuteTemplate(w, "home.html", data)
	})

	http.HandleFunc("/setup", handlers.Setup(tmpl.Lookup("setup.html")))
	http.HandleFunc("/login", handlers.Login(tmpl.Lookup("login.html")))
	http.HandleFunc("/logout", handlers.Logout())

	log.Printf("Starting filehost on %s\n", cfg.Port)
	log.Fatal(http.ListenAndServe(cfg.Port, nil))
}
