package ups

import (
	"git.openpdu.org/OpenPDU/openpdu/events"
	"git.openpdu.org/OpenPDU/openpdu/syslog"
	nut "github.com/robbiet480/go.nut"
	"github.com/spf13/viper"
)

var upsClient nut.Client
var ups nut.UPS
var Vars map[string]nut.Variable
var Connected bool

var defaults = map[string]interface{}{
	"Ups.Host":     "localhost",
	"Ups.Port":     3493,
	"Ups.Name":     "ups",
	"Ups.Username": "",
	"Ups.Password": "",
}

func init() {
	for k, v := range defaults {
		viper.SetDefault(k, v)
	}
	Connected = false
	events.AddListener("config_changed", Reconfigure)
}

func UpsConnect() {
	var username, password string
	var connectErr, authenticationError error
	var u nut.UPS

	upsClient, connectErr = nut.Connect(viper.GetString("Ups.Host"), viper.GetInt("Ups.Port"))
	if connectErr != nil {
		syslog.Err(connectErr.Error())
		return
	}

	if username = viper.GetString("Ups.Username"); username == "" {
		return
	}
	if password = viper.GetString("Ups.Password"); password == "" {
		return
	}

	_, authenticationError = upsClient.Authenticate(username, password)
	if authenticationError != nil {
		syslog.Err(authenticationError.Error())
		return
	}

	upsList, listErr := upsClient.GetUPSList()
	if listErr != nil {
		syslog.Err(listErr.Error())
		return
	}

	for _, u = range upsList {
		if u.Name == viper.GetString("Ups.Name") {
			ups = u
			Connected = true
			syslog.Notice("UPS connected")
			events.FireEvent("ups_connected")
			UpsReadVars()
		}
	}
}

func UpsReadVars() {
	Vars = map[string]nut.Variable{}
	for _, v := range ups.Variables {
		Vars[v.Name] = v
	}
}

func Reconfigure() {
	ups = nut.UPS{}
	upsClient = nut.Client{}
	syslog.Notice("UPS disconnected")
	events.FireEvent("ups_disconnected")
	Connected = false
	Vars = make(map[string]nut.Variable)
	go UpsConnect()
}
