package mqtt

import (
	"net"
	"time"
)

// Broker a mqtt broker
type Broker struct {
	mgr *Manager
}

// NewBroker create new broker
func NewBroker(p Provider) *Broker {
	// manager
	mgr := NewManager(p)

	handler := &Broker{mgr: mgr}
	return handler
}

// Handle tcp conn handle
func (b *Broker) Handle(conn net.Conn) {
	b.mgr.NewConn(conn)
}

// SendMessageToDevice send message to device
func (b *Broker) SendMessageToDevice(deviceid string, msgtype string, message []byte, timeout time.Duration) error {
	msg := &Publish{}
	msg.Header.QosLevel = QosAtLeastOnce
	msg.TopicName = msgtype
	msg.Payload = BytesPayload(message)
	return b.mgr.PublishMessage2Device(deviceid, msg, timeout)
}

// GetToken get device token with device id
func (b *Broker) GetToken(deviceid string) ([]byte, error) {
	return b.mgr.GetToken(deviceid)
}
