package messaging

import (
	"git.fjla.uk/owlboard/timetable-mgr/helpers"
	"git.fjla.uk/owlboard/timetable-mgr/log"
	"github.com/go-stomp/stomp/v3"
)

var Client *stomp.Conn

func StompInit(cfg *helpers.Configuration) {
	Client = dial(cfg.NrodUser, cfg.NrodPass)
}

// Connects the STOMP file to the Network Rail MQ Server
func dial(user, pass string) *stomp.Conn {
	conn, err := stomp.Dial("tcp", "publicdatafeeds.networkrail.co.uk:61618",
		stomp.ConnOpt.Login(user, pass),
		stomp.ConnOpt.HeartBeat(15000, 15000),
		stomp.ConnOpt.Header("client-id", user+"-mq-client"),
	)
	if err != nil {
		log.Msg.Fatal("Unable to connect to STOMP Client: " + err.Error())
		conn.MustDisconnect()
	}

	log.Msg.Info("Initialised STOMP Client")
	return conn
}

// Handles graceful disconnection of the STOMP client, falls back to
// a force disconnect if this fails.
func Disconnect(conn *stomp.Conn) {
	if conn != nil {
		err := conn.Disconnect()
		log.Msg.Warn("Disconnected STOMP Client")
		if err != nil {
			conn.MustDisconnect()
			log.Msg.Error("STOMP Disconnection failed, forced disconnect")
		}
		return
	}
	log.Msg.Error("STOMP Disconnect failed, next connection attempt may fail")
}

// Register against the MQ Server and log each message for testing purposes
