package handler

import (
	"net/http"
        "net/url"
)

func (h *Handler) showCurrentStatusJSView(w http.ResponseWriter, r *http.Request) {
	name := r.URL.Query().Get("name")
escName := url.PathEscape(name)
    w.Header().Set("Content-Type", "application/javascript")
	w.Write([]byte(`
document.write('<script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.6/dist/purify.min.js"><\/script>');
document.writeln('<div id="sillywordz"><div id="sillywordz-username"></div><div id="sillywordz-number"></div><div id="sillywordz-content"></div></div>');
fetch("https://sillywordz.kissing.computer/users/` + escName + `/status.json")
  .then( r => r.json() )
  .then( r => {
    if (!r.number || !r.content.length || r.number <1) {
      document.getElementById("sillywordz-content").innerHTML = "No updates yet."
      return
    }
 let safeAuthor = DOMPurify.sanitize(r.author);
    let safeContent = DOMPurify.sanitize(r.content);
    document.getElementById("sillywordz-username").innerHTML= '<a href="https://sillywordz.kissing.computer/users/` + escName + `status.json" target="_blank">' + safeAuthor  + '</a> ' + r.face + ' ' + r.timeAgo
    document.getElementById("sillywordz-number").innerHTML = "I wrote " + r.number + " words on my project!"
     if (r.number >= 1) {
      document.getElementById("sillywordz-content").innerHTML = "And I had this to say about it:" + safeContent
  }    })
`))
}

func (h *Handler) showCurrentStatusView(w http.ResponseWriter, r *http.Request) {
	logged, _ := h.getUser(r)
	name := r.URL.Query().Get("name")
	if name == "" {
		name = logged
	}
	h.renderLayout(w, "current_status", map[string]interface{}{
		"name": name,
	}, logged)
}
