package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"ttime/internal/config"
	"ttime/internal/database"

	_ "github.com/mattn/go-sqlite3"
)

// The button state as represented in memory
type ButtonState struct {
	PressCount int `json:"pressCount"`
}

// This is what a handler with a receiver looks like
// Keep in mind that concurrent state access is not (usually) safe
// And will in practice be guarded by a mutex
func (b *ButtonState) pressHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		b.PressCount++
	}

	response, err := json.Marshal(b)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	fmt.Println("Request received")
	io.WriteString(w, string(response))
}

// This is what a handler looks like
func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Request received")
	io.WriteString(w, "This is my website!\n")
}

func main() {
	conf, err := config.ReadConfigFromFile("config.toml")
	if err != nil {
		conf = config.NewConfig()
		conf.WriteConfigToFile("config.toml")
	}

	// Pretty print the current config
	str, _ := json.MarshalIndent(conf, "", "  ")
	fmt.Println(string(str))

	database.DbConnect(conf.DbPath)
	b := &ButtonState{PressCount: 0}

	// Mounting the handlers
	fs := http.FileServer(http.Dir("static"))
	http.Handle("/", fs)
	http.HandleFunc("/hello", handler)
	http.HandleFunc("/api/button", b.pressHandler)

	// Construct a server URL
	server_url := fmt.Sprintf(":%d", conf.Port)

	println("Server running on port", conf.Port)
	println("Visit http://localhost" + server_url)
	println("Press Ctrl+C to stop the server")

	err = http.ListenAndServe(server_url, nil)
	if err != nil {
		panic(err)
	}
}