package webui

import (
	"strings"

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

type MQTTReconfigFunction func()

var mqttReconfigFunction MQTTReconfigFunction

func SetMQTTReconfigFunction(f MQTTReconfigFunction) {
	mqttReconfigFunction = f
}

func mqttPage(ctx *macaron.Context) {
	ctx.Data["schema"] = viper.GetString("Mqtt.Schema")
	ctx.Data["host"] = viper.GetString("Mqtt.Host")
	ctx.Data["port"] = viper.GetString("Mqtt.Port")
	ctx.Data["clientid"] = viper.GetString("Mqtt.CliendID")
	ctx.Data["prefix"] = viper.GetString("Mqtt.Prefix")
	ctx.Data["username"] = viper.GetString("Mqtt.Username")
	ctx.Data["password"] = viper.GetString("Mqtt.Password")
	ctx.Data["lwttopic"] = viper.GetString("Mqtt.LWTTopic")
	ctx.Data["lwtonline"] = viper.GetString("Mqtt.LWTMessageOnline")
	ctx.Data["lwtoffline"] = viper.GetString("Mqtt.LWTMessageOffline")
	ctx.Data["homeassistant"] = viper.GetString("Mqtt.homeassistant")

	if mqtt.Connected() {
		ctx.Data["mqttstatus"] = "Connected"
	} else {
		ctx.Data["mqttstatus"] = "Disconnected"
	}

	ctx.Data["schemas"] = []string{"tcp", "ssl", "ws"}
	ctx.HTML(200, "mqtt")
}

type MQTTPostForm struct {
	Schema            string `form:"schema" binding:"Required"`
	Host              string `form:"host" binding:"Required"`
	Port              string `form:"port" binding:"Required"`
	Prefix            string `form:"prefix" binding:"Required"`
	ClientID          string `form:"clientid" binding:"Required"`
	Username          string `form:"username"`
	Password          string `form:"password"`
	LWTTopic          string `form:"lwttopic"`
	LWTMessageOnline  string `form:"lwtonline"`
	LWTMessageOffline string `form:"lwtoffline"`
	HomeAssistant     bool   `form:"homeassistant"`
}

func mqttPost(ctx *macaron.Context, f MQTTPostForm) {
	schema := strings.ToLower(strings.TrimSpace(f.Schema))
	switch schema {
	case
		"tcp",
		"ssl",
		"ws":
		viper.Set("Mqtt.Schema", schema)
	default:
		mqttPage(ctx)
		return
	}

	viper.Set("Mqtt.Host", strings.ToLower(strings.TrimSpace(f.Host)))
	viper.Set("Mqtt.Port", strings.ToLower(strings.TrimSpace(f.Port)))
	viper.Set("Mqtt.CliendID", strings.TrimSpace(f.ClientID))
	viper.Set("Mqtt.Prefix", strings.TrimSpace(f.Prefix))
	viper.Set("Mqtt.Username", strings.TrimSpace(f.Username))
	viper.Set("Mqtt.Password", f.Password)
	viper.Set("Mqtt.LWTTopic", strings.TrimSpace(f.LWTTopic))
	viper.Set("Mqtt.LWTMessageOnline", strings.TrimSpace(f.LWTMessageOnline))
	viper.Set("Mqtt.LWTMessageOffline", strings.TrimSpace(f.LWTMessageOffline))
	viper.Set("Mqtt.HomeAssistant", f.HomeAssistant)

	viper.WriteConfig()

	if mqttReconfigFunction != nil {
		go mqttReconfigFunction()
	}

	mqttPage(ctx)
}
