package stomp

import (
	"encoding/json"
	"log"

	"battlecamp-go-server/flag"

	"github.com/go-stomp/stomp"
)

var stompConnection *stomp.Conn

func getStompConnection() *stomp.Conn {
	if stompConnection == nil {
		var err error
		stompConnection, err = stomp.Dial("tcp", *flag.StompUrl)
		if(err != nil) {
			log.Printf("Error creating stomp connection error: %v\n", err)
		} else {
			log.Printf("Created stomp connection to %v", *flag.StompUrl)
		}
	}
	return stompConnection
}

func SendJson(topic string, v interface{}) {
	b, _ := json.Marshal(v)
	getStompConnection().Send("/topic/go-battlecamp."+topic, "application/json;charset=utf-8", b, stomp.SendOpt.NoContentLength)
}

func Subscribe(topic string) chan *stomp.Message {
	result, _ := getStompConnection().Subscribe("/topic/go-battlecamp."+topic, stomp.AckAuto)
	return result.C
}
