package zciyon

import (
	"net/http"
	"strings"
)

func SSEInit(w http.ResponseWriter) bool {
	_, ok := w.(http.Flusher)
	if !ok {
		return false
	}
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")
	w.Header().Set("X-Accel-Buffering", "no")
	return true
}
func SSESend_data(w http.ResponseWriter, data string, argid ...any) bool {
	id := ""
	if len(argid) > 0 {
		id = Tostr(argid[0])
	}
	msg := ""
	if id != "" {
		msg += "id: " + id + "\n"
	}
	msg += "data: " + strings.Replace(data, "\n", "<br/>", -1) + "\n\n"

	_, err := w.Write([]byte(msg))
	if err != nil {
		return false
	}
	w.(http.Flusher).Flush()
	return true
}

func SSESend_event(w http.ResponseWriter, data string, argevent ...string) bool {
	event := "_t_"
	if len(argevent) > 0 {
		event = argevent[0]
	}
	msg := "event: " + event + "\ndata: " + strings.Replace(data, "\n", "<br/>", -1) + "\n\n"
	_, err := w.Write([]byte(msg))
	if err != nil {
		return false
	}
	w.(http.Flusher).Flush()
	return true
}
