package main

import (
	"fmt"

	"github.com/AFASystems/presence/internal/pkg/bridge/mqtthandler"
	"github.com/AFASystems/presence/internal/pkg/config"
	"github.com/AFASystems/presence/internal/pkg/kafkaclient"
	"github.com/yosssi/gmq/mqtt"
	"github.com/yosssi/gmq/mqtt/client"
)

func main() {
	cfg := config.Load()

	cli := client.New(&client.Options{
		ErrorHandler: func(err error) {
			fmt.Println("Error in initiating MQTT client: ", err)
		},
	})
	defer cli.Terminate()

	err := cli.Connect(&client.ConnectOptions{
		Network:  "tcp",
		Address:  cfg.MQTTHost,
		ClientID: []byte(cfg.MQTTClientID),
		UserName: []byte(cfg.MQTTUser),
		Password: []byte(cfg.MQTTPass),
	})

	if err != nil {
		fmt.Println("Could not connect to MQTT broker")
		panic(err)
	}

	fmt.Println("Successfuly connected to MQTT broker")

	writer := kafkaclient.KafkaWriter(cfg.KafkaURL, "rawbeacons")
	defer writer.Close()

	err = cli.Subscribe(&client.SubscribeOptions{
		SubReqs: []*client.SubReq{
			{
				TopicFilter: []byte("publish_out/#"),
				QoS:         mqtt.QoS0,
				Handler: func(topicName, message []byte) {
					mqtthandler.MqttHandler(writer, topicName, message)
				},
			},
		},
	})
	if err != nil {
		panic(err)
	}

	select {}
}
