package main

import (
	"sync"

	MQTT "github.com/eclipse/paho.mqtt.golang"
	"gitlab.imt-atlantique.fr/xaal/code/go/core/uuid"
	"gitlab.imt-atlantique.fr/xaal/code/go/core/xaal"
)

type Gateway struct {
	client   MQTT.Client
	engine   *xaal.Engine
	devices  map[string]*Z2MDevice
	baseAddr uuid.UUID
}

var (
	instance *Gateway
	once     sync.Once
)

func GetGW() *Gateway {
	once.Do(func() {
		instance = &Gateway{devices: make(map[string]*Z2MDevice)}
	})
	return instance
}

func NewGW(client MQTT.Client, cfg *Config) *Gateway {
	gw := GetGW()
	gw.baseAddr = cfg.baseAddr
	gw.client = client
	return gw
}

func (gw *Gateway) GetZDevice(name string) *Z2MDevice {
	return gw.devices[name]
}

func (gw *Gateway) AddZDevice(zDev *Z2MDevice) {
	gw.devices[zDev.FriendlyName] = zDev
}

func (gw *Gateway) GetZDevices() map[string]*Z2MDevice {
	return gw.devices
}

func (gw *Gateway) GetZDeviceByTopic(topic string) *Z2MDevice {
	name := topic[len(mqttTopic+"/"):]
	return gw.GetZDevice(name)
}