package org.example.demo.praktikum3;

import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import jakarta.jms.ConnectionFactory;
import jakarta.jms.JMSConsumer;
import jakarta.jms.JMSContext;
import jakarta.jms.Topic;

public class MessageReceiver extends Thread {
    private JTextArea text;
    private Topic topic;
    private ConnectionFactory cf;

    public MessageReceiver(Topic topic, ConnectionFactory cf, JTextArea text) {
        this.text = text;
        this.topic = topic;
        this.cf = cf;
    }

    public JTextArea getText() {
        return text;
    }

    public void setText(JTextArea text) {
        this.text = text;
    }

    public void run() {
        try (JMSContext context = cf.createContext("guest", "guest")) {
            JMSConsumer consumer = context.createConsumer(topic);
            while (true) {
                String message = consumer.receiveBody(String.class);
                if (message != null) {
                    SwingUtilities.invokeLater(() -> text.append(message + "\n"));
                }
            }
        }
    }
}
