package main

import (
	"fmt"
	"html/template"
	"net/http"
	"os"
	"time"

	"nextbook/pkg/storygraph"

	"github.com/joho/godotenv"
)

var (
	port string
)

func init() {
	godotenv.Load(os.Getenv("DOTENV_DIR") + ".env")

	var ok bool
	port, ok = os.LookupEnv("PORT")
	if !ok {
		port = "8000"
	}
}

func main() {
	latestBooks := map[string]*[]storygraph.Book{}
	refreshingBooks := true
	var lastUpdated *time.Time

	updateBooks := func() {
		refreshingBooks = true
		defer func() { refreshingBooks = false }()
		newBookList, err := storygraph.GetLatestBooks()
		if err != nil {
			fmt.Println("Error fetching latest books:", err)
			return
		}

		// Update each category individually with books we have managed to find
		for cat, books := range newBookList {
			if b, ok := newBookList[cat]; ok && b != nil {
				latestBooks[cat] = books
			}
		}
		now := time.Now()
		lastUpdated = &now
		fmt.Println("Updated latest book recommendations")
	}

	go func() {
		for {
			updateBooks()
			time.Sleep(1 * time.Hour)
		}
	}()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		type data struct {
			Books       map[string]*[]storygraph.Book
			LastUpdated string
			Refreshing  bool
		}
		d := data{
			Books:       latestBooks,
			LastUpdated: "",
			Refreshing:  refreshingBooks,
		}
		if lastUpdated != nil {
			d.LastUpdated = lastUpdated.Format(time.RFC1123)
		}
		tmpl := template.Must(template.ParseFiles("templates/index.html"))
		tmpl.Execute(w, d)
	})
	http.HandleFunc("/refresh", func(w http.ResponseWriter, r *http.Request) {
		go updateBooks()
		w.Header().Set("Location", "/")
		w.Header().Set("Refresh", "0; url=/")
		w.Write([]byte("Refreshing..."))
	})
	http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
	http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
}
