package ui
import (
"bytes"
"fmt"
"html/template"
"io"
"net/http"
"path/filepath"
"sort"
"git.faercol.me/faercol/http-boot-server/bootserver/helpers"
"git.faercol.me/faercol/http-boot-server/bootserver/services"
"github.com/sirupsen/logrus"
)
const UIRoute = "/"
type templateBootOption struct {
ID string
Name string
Path string
DiskID string
Selected bool
}
type templateClient struct {
ID string
Name string
BootOptions []templateBootOption
}
type templateData struct {
Clients []templateClient
}
type UIController struct {
clientService *services.ClientHandlerService
l *logrus.Logger
}
func NewUIController(l *logrus.Logger, service *services.ClientHandlerService) *UIController {
return &UIController{
clientService: service,
l: l,
}
}
func (uc *UIController) serveUI(w http.ResponseWriter, r *http.Request) (int, int, error) {
lp := filepath.Join("templates", "index.html")
tmpl, err := template.ParseFiles(lp)
if err != nil {
return http.StatusInternalServerError, -1, fmt.Errorf("failed to init template: %w", err)
}
buf := new(bytes.Buffer)
clients, err := uc.clientService.GetAllClientConfig()
if err != nil {
return http.StatusInternalServerError, -1, fmt.Errorf("failed to get list of clients: %w", err)
}
dat := templateData{Clients: []templateClient{}}
for _, clt := range clients {
tplBO := []templateBootOption{}
for id, bo := range clt.Options {
tplBO = append(tplBO, templateBootOption{
Name: bo.Name,
Path: bo.Path,
ID: id,
DiskID: bo.DiskID,
Selected: id == clt.SelectedOption,
})
sort.Slice(tplBO, func(i, j int) bool {
return tplBO[i].ID < tplBO[j].ID
})
}
dat.Clients = append(dat.Clients, templateClient{
ID: clt.ID.String(),
Name: clt.Name,
BootOptions: tplBO,
})
}
if err := tmpl.Execute(buf, dat); err != nil {
return http.StatusInternalServerError, -1, fmt.Errorf("failed to execute template: %w", err)
}
n, err := io.Copy(w, buf)
if err != nil {
return http.StatusInternalServerError, int(n), fmt.Errorf("failed to write response; %w", err)
}
return http.StatusOK, int(n), nil
}
func (uc *UIController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.RequestURI != "/" {
uc.l.Errorf("Unhandled route %q", r.RequestURI)
helpers.HandleResponse(w, r, http.StatusNotFound, nil, uc.l)
return
}
returncode, contentLength, err := uc.serveUI(w, r)
if err != nil {
uc.l.Errorf("Error serving UI: %s", err.Error())
helpers.HandleResponse(w, r, returncode, nil, uc.l)
} else {
helpers.AddToContext(r, returncode, contentLength)
}
}