package dyn

import (
	"ciyon/web/admin"
	c "ciyon/zciyon"
	"net/http"
	"time"
)

func SSE_get(w http.ResponseWriter, r *http.Request) bool {
	if !c.SSEInit(w) {
		w.Write([]byte("不支持SSE Flush"))
		return false
	}
	post := c.NewCiyPost(w, r)
	rsuser, err := admin.Verifyuser(r, c.CiyDB, post)
	if err != nil {
		c.SSESend_event(w, "请重新登录")
		return false
	}
	if admin.Nopower(c.CiyDB, c.Toint(rsuser["id"]), "p610r") {
		c.SSESend_event(w, "您未被授权操作")
		return false
	}
	param := post.Get("bb")
	c.SSESend_data(w, param)
	for i := 0; i < 100; i++ {
		if i%10 == 1 {
			c.SSESend_data(w, "sse: "+c.Tostr(i), i)
		}
		if !c.SSESend_event(w, c.Tostr(i)) {
			return true
		}
		c.Sleep(0.05)
	}
	c.SSESend_event(w, "ok")
	return true
}

func SSE_get_ch(w http.ResponseWriter, r *http.Request) bool {
	if !c.SSEInit(w) {
		w.Write([]byte("不支持SSE Flush"))
		return false
	}
	post := c.NewCiyPost(w, r)
	rsuser, err := admin.Verifyuser(r, c.CiyDB, post)
	if err != nil {
		c.SSESend_event(w, "请重新登录")
		return false
	}
	if admin.Nopower(c.CiyDB, c.Toint(rsuser["id"]), "p610r") {
		c.SSESend_event(w, "您未被授权操作")
		return false
	}
	param := post.Get("param")
	c.SSESend_data(w, param)

	done := r.Context().Done()
	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-done:
			return false
		case <-ticker.C:
			if !c.SSESend_data(w, time.Now().Format(time.RFC3339)) {
				return true
			}
		}
	}
}
