package web

import (
	"html/template"
	"net/http"
	"strconv"
)

type RelaisData struct {
	ID    int
	Name  string
	State bool
}

// TemplateData erweitern um Version und Datum
type TemplateData struct {
	V1        float64
	V2        float64
	Relais    []RelaisData
	Version   string
	BuildDate string
}

type Server struct {
	port         string
	readVoltFunc func(channel int) float64
	toggleFunc   func(id int)
	getRelais    func() []RelaisData
	versionFunc  func() (string, string) // Neu hinzugefügt
}

// NewServer um das version-Callback erweitern
func NewServer(port string, readVolt func(int) float64, toggle func(int), getRelais func() []RelaisData, getVersion func() (string, string)) *Server {
	return &Server{
		port:         port,
		readVoltFunc: readVolt,
		toggleFunc:   toggle,
		getRelais:    getRelais,
		versionFunc:  getVersion,
	}
}

func (s *Server) Start() error {
	http.HandleFunc("/", s.handleIndex)
	http.HandleFunc("/toggle", s.handleToggle)
	return http.ListenAndServe(s.port, nil)
}

func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
	v1 := s.readVoltFunc(0)
	v2 := s.readVoltFunc(1)
	ver, date := s.versionFunc() // Version abfragen

	tmpl, err := template.ParseFiles("web/static/index.html")
	if err != nil {
		http.Error(w, "Template nicht gefunden: "+err.Error(), http.StatusInternalServerError)
		return
	}

	data := TemplateData{
		V1:        v1,
		V2:        v2,
		Relais:    s.getRelais(),
		Version:   ver,  // Daten an Template übergeben
		BuildDate: date, // Daten an Template übergeben
	}
	tmpl.Execute(w, data)
}

func (s *Server) handleToggle(w http.ResponseWriter, r *http.Request) {
	idStr := r.URL.Query().Get("id")
	id, err := strconv.Atoi(idStr)
	if err == nil {
		s.toggleFunc(id)
	}
	http.Redirect(w, r, "/", http.StatusSeeOther)
}
