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

public class Chat implements MessageListener {
    ConnectionFactory tcf = null; 
    Destination chatDest = null;

	public void onMessage(Message msg) {
		try {
			if(msg instanceof TextMessage) {
				TextMessage receiveMsg = (TextMessage)msg;
				System.out.println(receiveMsg.getText());
			}
		} catch (JMSException jmse) {
			jmse.printStackTrace();
		}
	}

	public void userInput(String clientName) {
	    try {
	      InitialContext ctx = new InitialContext();
	      Object tmp = ctx.lookup("ConnectionFactory");
	      tcf = (ConnectionFactory) tmp;
	      tmp = ctx.lookup("topic/MinuTopic");
	      chatDest = (Destination) tmp;
	      ctx.close();
	    } catch (javax.naming.NamingException ne) {
	      System.out.println("Exception: " + ne.getMessage());
	      System.exit(1);
	    }
		
		try {

		    Connection tconn = tcf.createConnection();
		    tconn.setClientID(clientName);
		    Session tsession = tconn.createSession(false, 
								Session.AUTO_ACKNOWLEDGE);

		    String msgSelector = "Channel='General' or Channel='" + clientName + "'";
			System.out.println("MessageSelector: " + msgSelector);

		    MessageConsumer subscriber = tsession.createConsumer(chatDest, msgSelector, true);
		    //TopicSubscriber subscriber = tsession.createDurableSubscriber(chatDest, clientName, msgSelector, true);
		    subscriber.setMessageListener(this);
		    MessageProducer pub = tsession.createProducer(chatDest);

			tconn.start();
	    
			 BufferedReader in
			   = new BufferedReader(new InputStreamReader(System.in));
			String input = null;
			
			TextMessage sendMsg = tsession.createTextMessage();
			while(true) {
				System.out.print("> ");
				System.out.flush();
				input = in.readLine();
				
				if(input.trim().length() == 0) {
					continue;
				}
				String[] splits = input.split("\\s");
				if(splits[0].startsWith("#")) {
					String sendToClient=splits[1];
					System.out.println("Sending to client " + sendToClient);
					sendMsg.setStringProperty("Channel", sendToClient);
				} else {
					sendMsg.setStringProperty("Channel", "General");
				}
				sendMsg.setText(input);	
				
				//pub.publish(sendMsg);
				pub.send(sendMsg);
			}
		} catch (JMSException ex) {
			System.out.println("Error: " + ex.getMessage());
		} catch (IOException e) {}
	}
	
  public static void main(String[] args) {
	Chat chat = new Chat();
	String clientName="Default";
	if (args.length > 0) {
		clientName = args[0];
	}
	chat.userInput(clientName);
  }
}

