import java.io.*;
import javax.jms.*;
import javax.naming.*;

public class JMSChat implements Runnable
{
	protected String username = "Anonymous";
	protected TopicConnection connection;
	protected Topic topic;
	protected TopicSession session;
	protected TopicSubscriber subscriber;
	protected TopicPublisher publisher;

	public static void main(String[] args)
	{
		try
		{
			TopicConnectionFactory factory = (TopicConnectionFactory)new InitialContext().lookup("java:comp/env/jms/theTopicConnectionFactory");

			TopicConnection connection = factory.createTopicConnection();

			Topic topic = (Topic)new InitialContext().lookup("java:comp/env/jms/theTopic");

			JMSChat chat = new JMSChat(connection, topic);
			
			if(args.length > 0)
				chat.setUsername(args[0]);

			chat.run();
		}
		catch(JMSException e)
		{
			System.err.println("Communication error: " + e.getMessage());
		}
		catch(NamingException e)
		{
			System.err.println("Error looking up objects: " + e.getMessage());
		}
	}
	
	public JMSChat(TopicConnection connection, Topic topic) throws JMSException
	{
		this.connection = connection;
		this.session = connection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
		this.topic = topic;
		
		this.subscriber = session.createSubscriber(topic, null, true);
		this.publisher = session.createPublisher(topic);
		
	}

	public void setUsername(String username)
	{
		this.username = username;
	}

	public void run()
	{
		try
		{
			connection.start();

			new Thread(new Runnable() { public void run() { JMSChat.this.listen(); } }).start();

			System.out.println("*** LOGGED IN AS " + this.username + " ****");
			BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

			while(true)
			{
				String line = reader.readLine();
				
				TextMessage message = session.createTextMessage();
				message.setStringProperty("sender", this.username);
				message.setText(line);
				
				publisher.publish(message);
			}
		}
		catch(JMSException e)
		{
			System.err.println("Communication error: " + e.getMessage());
		}
		catch(IOException e)
		{
			System.err.println("Error reading from System in");
		}
	}

	protected void listen()
	{
		try
		{
			while(true)
			{
				Message message = subscriber.receive();
				
				if(message instanceof TextMessage)
				{
					System.out.println(message.getStringProperty("sender") + ": " +
									   ((TextMessage)message).getText());
				}
			}
		}
		catch(JMSException e)
		{
			System.err.println("Communication error: " + e.getMessage());
		}
	}
}
