package node

import (
	"fmt"
	"net/http"
	"text/template"
)

const debugText = `<html>
<head>
 <style type="text/css">
.info th { text-align: right; }
.error { color: red; }
 </style>
</head>
<body>
 <title>Node status: {{.Name}}</title>
 <table class="info">
  <tr>
   <th>Name:</th>
   <td>{{.Name}}</td>
  </tr>
  <tr>
   <th>Master:</th>
   <td>{{if .IsMaster}}YES{{else}}NO{{end}}</td>
  </tr>
  <tr>
   <th>Icecast:</th>
   <td>{{if .IcecastUp}}OK{{else}}<span class="error">DOWN</span>{{end}}</td>
  </tr>
  <tr>
   <th>Bandwidth:</th>
   <td>{{.BandwidthUsage}}%</td>
  </tr>
  <tr>
   <th></th>
   <td></td>
  </tr>
 </table>
 <h3>Transcoders</h3>
 {{if .Transcoders}}
 <table>
  <tr>
   <th>Source</th>
   <th>Target</th>
   <th>Mount</th>
   <th>Format</th>
   <th>Bitrate/Q</th>
  </tr>
  {{range .Transcoders}}
  <tr>
   <td>{{.SourceURL}}</td>
   <td>{{.TargetIP}}:{{.TargetPort}}</td>
   <td>{{.TargetMount}}</td>
   <td>{{.Format}}</td>
   <td>{{if gt .BitRate 0}}{{.BitRate}}{{else}}{{.Quality}}{{end}}</td>
  </tr>
  {{end}}
 </table>
 {{else}}
 <p>No active transcoders on this node.</p>
 {{end}}
</body>
</html>`

var (
	debugTmpl = template.Must(template.New("node debug").Parse(debugText))
)

// ServeHTTP serves the debug console.
func (rc *RadioNode) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	rc.transcodersMx.Lock()
	var transcoders []*transcoder
	for _, t := range rc.transcoders {
		transcoders = append(transcoders, t)
	}
	rc.transcodersMx.Unlock()

	ctx := struct {
		Name           string
		IsMaster       bool
		IcecastUp      bool
		BandwidthUsage float64
		Transcoders    []*transcoder
	}{
		Name:           rc.name,
		IsMaster:       rc.me.IsMaster(),
		IcecastUp:      rc.icecast.GetStatus().Up,
		BandwidthUsage: rc.bw.GetUsage(),
		Transcoders:    transcoders,
	}
	err := debugTmpl.Execute(w, &ctx)
	if err != nil {
		fmt.Fprintln(w, "debug: error executing template: ", err.Error())
	}
}