package webui

import (
	"net/http"
	"strconv"

	"git.openpdu.org/OpenPDU/openpdu/outlet"
	"gopkg.in/macaron.v1"
)

func statusPage(ctx *macaron.Context) {
	ctx.HTML(200, "status") // 200 is the response code.
}

func jsonStatus(ctx *macaron.Context) {
	// MQTTpublish("openpdu/status", "asdss")

	var data = make([]Dictionary, 0)
	var o *outlet.Outlet
	for i := range outlet.Outlets {
		o = outlet.Outlets[i]
		//		d := []string{fmt.Sprintf("%d", o.Num), o.Channel.Name, fmt.Sprintf("%v", o.Channel.Value)}
		data = append(data, Dictionary{
			"Num":         o.Num,
			"Description": o.Description,
			"Status":      o.Channel.Status(),
		})
	}

	ctx.JSON(http.StatusOK, Dictionary{
		"data": data,
	})
}

func jsonOutletToggle(ctx *macaron.Context) {
	var err error
	var num uint64
	var o *outlet.Outlet

	num, err = strconv.ParseUint(ctx.Params(":id"), 10, 64)
	if err != nil {
		ctx.JSON(http.StatusOK, Dictionary{
			"data": "error1",
		})
	}

	if num >= uint64(len(outlet.Outlets)) || num < 0 {
		ctx.JSON(http.StatusOK, Dictionary{
			"data": "error2",
		})
	}

	o = outlet.Outlets[num]
	_, err = o.Channel.Toggle()
	if err != nil {
		ctx.JSON(http.StatusOK, Dictionary{
			"data": "error3",
		})
	}

	ctx.JSON(http.StatusOK, Dictionary{
		"data": "ok",
	})
}
