package webui

import (
	"strings"

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

func upsPage(ctx *macaron.Context) {
	ctx.Data["host"] = viper.GetString("Ups.Host")
	ctx.Data["port"] = viper.GetInt("Ups.Port")
	ctx.Data["upsname"] = viper.GetString("Ups.Name")
	ctx.Data["username"] = viper.GetString("Ups.Username")
	ctx.Data["password"] = viper.GetString("Ups.Password")

	if ups.Connected {
		ctx.Data["serverstatus"] = "Connected"
	} else {
		ctx.Data["serverstatus"] = "Disconnected"
	}

	ctx.Data["upsstatus"] = ups.Vars["ups.status"].Value
	ctx.Data["upsmfr"] = ups.Vars["device.mfr"].Value
	ctx.Data["upsmodel"] = ups.Vars["device.model"].Value
	ctx.Data["upsserial"] = ups.Vars["device.serial"].Value
	ctx.Data["upsload"] = ups.Vars["ups.load"].Value
	ctx.Data["upscharge"] = ups.Vars["battery.charge"].Value

	ctx.HTML(200, "ups")
}

type UPSPostForm struct {
	Host     string `form:"host" binding:"Required"`
	Port     int    `form:"port" binding:"Required"`
	UpsName  string `form:"upsname" binding:"Required"`
	Username string `form:"username" binding:"Required"`
	Password string `form:"password" binding:"Required"`
}

func upsPost(ctx *macaron.Context, f UPSPostForm) {
	viper.Set("Ups.Host", strings.ToLower(strings.TrimSpace(f.Host)))
	viper.Set("Ups.Port", f.Port)
	viper.Set("Ups.Name", strings.TrimSpace(f.UpsName))
	viper.Set("Ups.Username", strings.TrimSpace(f.Username))
	viper.Set("Ups.Password", f.Password)
	viper.WriteConfig()

	upsPage(ctx)
}
