package board

import (
	"errors"

	MQTT "github.com/eclipse/paho.mqtt.golang"
	"github.com/spf13/viper"
)

var boardCreatorFunctions = make(map[string]BoardCreatorFunction)

var AllChannels = make(map[string]Channel)

type BoardCreatorFunction func(*viper.Viper, string) *Board
type onChannelUpdateFunction func(oldValue bool, c Channel)

type Board interface {
	Initialize()
	Dump()
	Channel(uint64) Channel
}

type Channel interface {
	Toggle() (bool, error)
	On() error
	Off() error
	ToString() string
	Status() bool
	Parent() Board
	Dump()
	Name() string
	OnBoot() string
	SetOnBoot(string)
	SetMQTTStateTopic(string)
	SetMQTTCommandTopic(string)
	MQTTStateTopic() string
	MQTTCommandTopic() string
	MQTTHandler(MQTT.Client, MQTT.Message)
	AddOnChannelUpdateFunction(string, onChannelUpdateFunction)
}

func RegisterBoardType(name string, fun BoardCreatorFunction) {
	boardCreatorFunctions[name] = fun
}

func CreateBoard(cfg *viper.Viper, key string) (Board, error) {
	var createNewBoard BoardCreatorFunction
	var ok bool

	boardType := cfg.GetString("type")
	createNewBoard, ok = boardCreatorFunctions[boardType]

	if !ok {
		return nil, errors.New("unknown board type")
	}

	return *createNewBoard(cfg, key), nil
}
