package main

import (
	"git.openpdu.org/OpenPDU/openpdu/board"
	"git.openpdu.org/OpenPDU/openpdu/mqtt"
	"git.openpdu.org/OpenPDU/openpdu/syslog"
	"github.com/spf13/viper"
)

var boards []*board.Board

func CreateBoards() {

	// AllChannels = make(map[string]Channel)

	boardsConfig := viper.Sub("boards")
	if boardsConfig == nil {
		syslog.Warning("No board configured")
		return
	}

	for key := range boardsConfig.AllSettings() {
		boardConfig := boardsConfig.Sub(key)
		boardConfig.SetDefault("type", "dummy")

		b, err := board.CreateBoard(boardConfig, key)
		if err == nil {
			boards = append(boards, &b)
		}
	}

	for i := range board.AllChannels {
		board.AllChannels[i].AddOnChannelUpdateFunction(
			"mqtt-publish",
			func(oldValue bool, c board.Channel) {
				mqtt.Publish(c.MQTTStateTopic(), c.ToString())
			})
	}

	// TODO: init boards array?

	//	outlets = make([]*Outlet, len(allChannels))

	// // dumpa tutto
	// for b := range boards {
	// 	boards[b].Dump()
	// }

	// // dumpa tutto
	// for o := range outlets {
	// 	outlet.Outlets[o].Dump()
	// }

}

func InitBoards() {
	var b board.Board
	for i := range boards {
		b = *boards[i]
		go b.Initialize()
	}
}
