package webui

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"git.openpdu.org/OpenPDU/openpdu/outlet"
	"github.com/spf13/viper"
	"gopkg.in/macaron.v1"
)

func outletsPage(ctx *macaron.Context) {

	ctx.Data["outlets"] = outlet.Outlets

	ctx.HTML(200, "outlets")
}

type OutletPostForm struct {
	Description      string `form:"description" binding:"Required"`
	MQTTStateTopic   string `form:"mqttstatetopic"`
	MQTTCommandTopic string `form:"mqttcommandtopic"`
	OnBoot           string `form:"onboot" binding:"Required"`
}

func outletEditPage(ctx *macaron.Context) {
	var err error
	var num uint64
	var o *outlet.Outlet
	num, err = strconv.ParseUint(ctx.Params(":num"), 10, 64)
	if err != nil {
		ctx.JSON(http.StatusOK, Dictionary{
			"result": "error",
			"error":  err.Error(),
		})
		return
	}

	o = outlet.Outlets[num]
	ctx.Data["outlet"] = o

	ctx.Data["onboot_values"] = []string{"on", "off", "last"}
	ctx.HTML(200, "outlet_edit")
}

func outletEditPost(ctx *macaron.Context, f OutletPostForm) {
	var err error
	var num uint64

	num, err = strconv.ParseUint(ctx.Params(":num"), 10, 64)
	if err != nil {
		ctx.JSON(http.StatusOK, Dictionary{
			"result": "error",
			"error":  err.Error(),
		})
		return
	}

	onboot := "on"
	onbootForm := strings.ToLower(strings.TrimSpace(f.OnBoot))
	switch onbootForm {
	case
		"on",
		"off",
		"last":
		onboot = onbootForm
	default:
		outletsPage(ctx)
		return
	}
	outlet.Outlets[num].Channel.SetOnBoot(onboot)

	outlet.Outlets[num].Description = strings.TrimSpace(f.Description)
	s2 := fmt.Sprintf("outlets.%s.description", outlet.Outlets[num].ID)
	viper.Set(s2, outlet.Outlets[num].Description)

	mqttstate := strings.TrimSpace(f.MQTTStateTopic)
	if mqttstate == "" {
		mqttstate = outlet.Outlets[num].Channel.Name()
	}
	outlet.Outlets[num].Channel.SetMQTTStateTopic(mqttstate)

	mqttcommand := strings.TrimSpace(f.MQTTCommandTopic)
	if mqttcommand == "" {
		mqttcommand = outlet.Outlets[num].Channel.Name()
	}
	outlet.Outlets[num].Channel.SetMQTTCommandTopic(mqttcommand)

	viper.WriteConfig()

	ctx.Redirect("/outlets")
}
