package org.example.demo.praktikum3;

import jakarta.jms.ConnectionFactory;
import jakarta.jms.JMSContext;
import jakarta.jms.JMSProducer;
import jakarta.jms.TextMessage;
import jakarta.jms.Topic;

public class MessageSender {
    private String prefix;
    private Topic topic;
    private ConnectionFactory cf;

    public MessageSender(Topic topic, ConnectionFactory cf, String prefix) {
        this.topic = topic;
        this.cf = cf;
        this.prefix = prefix;
    }

    public void sendMessage(String msg) {
        var text = prefix + msg;

        try (JMSContext context = cf.createContext("guest", "guest")) {
            JMSProducer producer = context.createProducer();
            TextMessage message = context.createTextMessage(text);
            producer.send(topic, message);
            System.out.println("Message '"+text+"' sent successfully.");
        }
        catch (Exception e) {
            System.out.println("Message '"+text+"' couldn't be sent: " + e);
        }
    }
}
