package var.mom.jms.chat;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Scanner;

// Code aus JMS-Client mit Umbenennung des Typs von JMSClient zu ChatClient und Anpassung des packages
public class ChatClient implements MessageListener {
	private Connection connection;
	private Session session;
	private MessageConsumer consumer;
    private MessageProducer producer;

	public ChatClient() throws NamingException, JMSException {
		Context ctx = new InitialContext();
		ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory");
		Destination queue = (Destination) ctx.lookup(Conf.QUEUE);
		connection = factory.createConnection();
		session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        producer = session.createProducer(queue);

		consumer = session.createConsumer(queue);
		consumer.setMessageListener(this);
		connection.start();
	}

	@Override
	public void onMessage(Message message) {
		try {
			if (message instanceof TextMessage) {
				TextMessage textMessage = (TextMessage) message;
				String messageText = textMessage.getText();
				String userName = textMessage.getStringProperty("Name");
				System.out.println(userName + ": " + messageText);
			}
		} catch (JMSException e) {
			System.err.println(e);
		}
	}

    public void sendMessage(String messageText, String userName) throws JMSException {
        TextMessage textMessage = session.createTextMessage();

        textMessage.setText(messageText);
        textMessage.setStringProperty("Name", userName);

        producer.send(textMessage);
    }

	public static void main(String[] args) {
		//long wait = Long.parseLong(args[0]);
		ChatClient node = null;
        String userName = "Nastja";
		try {
			node = new ChatClient();

            while(true) {
                Scanner keyboard = new Scanner(System.in);
                //System.out.println("> ");
                String messageText = keyboard.nextLine();
                System.out.println("");
                node.sendMessage(messageText, userName);
            }

		} catch ( NamingException | JMSException e) {
			System.err.println(e);
		} finally {
			try {
				if (node != null && node.consumer != null)
					node.consumer.close();
				if (node != null && node.session != null)
					node.session.close();
				if (node != null && node.connection != null)
					node.connection.close();
			} catch (JMSException e) {
				System.err.println(e);
			}
		}
	}
}
