package main

import (
	"net/http"

	"gopkg.in/macaron.v1"
)

func statusPage(ctx *macaron.Context) {
	var pluglist []Dictionary

	for num, o := range TheConfig.Outlets {
		pluglist = append(pluglist, Dictionary{"id": num, "description": o.Name})
	}

	ctx.Data["pluglist"] = pluglist
	ctx.HTML(200, "status") // 200 is the response code.
}

//SettingsMQTTForm definition
type SettingsMQTTForm struct {
	BrokerIP      string `form:"brokerip" binding:"Required"`
	BrokerPort    string `form:"brokerport" binding:"Required"`
	ClientID      string `form:"clientid" binding:"Required"`
	Username      string `form:"username"`
	Password      string `form:"password"`
	Topic         string `form:"topic" binding:"Required"`
	CleanSession  bool   `form:"cleansession"`
	HomeAssistant bool   `form:"homeassistant"`
}

func webGETSettingsMQTT(ctx *macaron.Context) {
	ctx.Data["r_brokerip"] = TheConfig.MQTT.BrokerIP
	ctx.Data["r_brokerport"] = TheConfig.MQTT.BrokerPort
	ctx.Data["r_clientid"] = TheConfig.MQTT.ClientID
	ctx.Data["r_username"] = TheConfig.MQTT.Username
	ctx.Data["r_password"] = TheConfig.MQTT.Password
	ctx.Data["r_cleansession"] = TheConfig.MQTT.CleanSession
	ctx.Data["r_topic"] = TheConfig.MQTT.Topic
	ctx.Data["r_homeassistant"] = TheConfig.MQTT.HomeAssistant
	ctx.HTML(200, "settings_mqtt") // 200 is the response code.
}

func webPOSTSettingsMQTT(ctx *macaron.Context, f SettingsMQTTForm) {

	TheConfig.MQTT.BrokerIP = f.BrokerIP
	TheConfig.MQTT.BrokerPort = f.BrokerPort
	TheConfig.MQTT.ClientID = f.ClientID
	TheConfig.MQTT.Username = f.Username
	TheConfig.MQTT.Password = f.Password
	TheConfig.MQTT.Topic = f.Topic
	// TODO: cleansession
	// TODO: homeassistant

	err := writeConfig()
	if err != nil {
		ctx.JSON(http.StatusOK, Dictionary{
			"result": "error",
			"error":  err.Error(),
		})
	}

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