package main

import (
	"fmt"
	"net/http"
)

// based on https://community.hetzner.com/tutorials/real-time-apps-with-go-and-reactjs/server-sent-events

var clientChannels = make(map[chan []byte]bool)

// StartHTTPServer starts the HTTP server to provide the monitoring page.
func StartHTTPServer() error {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, indexPath)
	})
	http.HandleFunc("/sse", sseHandler)

	if err := http.ListenAndServe(":4000", nil); err != nil {
		return err
	}

	return nil
}

func sseHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Connection", "keep-alive")
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Access-Control-Allow-Origin", "*")

	clientChannel := make(chan []byte)
	clientChannels[clientChannel] = true

	for {
		select {
		case update := <-clientChannel:
			test := fmt.Sprintf("data: %s\n\n", string(update))
			w.Write([]byte(test))
			w.(http.Flusher).Flush()
		case <-r.Context().Done():
			delete(clientChannels, clientChannel)
			return
		}
	}
}
