package org.distributed;
import java.util.Scanner;
import javax.jms.*;
import org.apache.activemq.ActiveMQConnectionFactory;

public class ChatHandler {

    private String userId, corespondent;
    private Connection connection;
    private Session senderSession, receiverSession;
    private final String TAG = "Task2_queue_";
    private final String BROKER_URL = "tcp://localhost:61616";
    /**
     * Initialize JMS session
     * @throws JMSException
     */
    public void initializeSession() throws JMSException {
        ConnectionFactory factory = new ActiveMQConnectionFactory(BROKER_URL);
        this.connection = factory.createConnection();
        this.connection.start();
        this.senderSession = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        this.receiverSession = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    }

    /**
     * Start conversation loop
     * @param sc
     * @throws JMSException
     */
    public void startConversation(Scanner sc) throws JMSException {

        // init receiving thread
        Thread t = setupReceiver(userId);

        // Continuous input loop
        try {
            while (sc.hasNextLine()){

                // handle user input and send messages
                // or if exit command, break loop
                if(!respond(sc)){ 
                    break;
                }
            }
        } catch (Exception e) {
            System.err.println("Error in continuous conversation: " + e.getMessage());
        } finally {
            t.interrupt();
        }
    }

    /**
     * Handle user input and send messages
     * @param sc
     * @throws JMSException
     */
    private boolean respond(Scanner sc) throws JMSException {
        String line = sc.nextLine();

        // exit condition
        if (line.equalsIgnoreCase("exit")) {
            System.out.println("Exiting conversation...");
            return false;
        }

        // Send message to receiver
        sendMessage(createProducer(corespondent), line);
        return true;
    }


    // Setup producer and consumer for a receiver
    private Thread setupReceiver(String receiver) throws JMSException {
        MessageConsumer contact = createConsumer();

        // add consumer to contacts map
        return getThread(contact);
    }

    /**
     * Create a producer for a given contact ID so we can send messages
     * @param id
     * @return MessageProducer
     * @throws JMSException
     */
    private MessageProducer createProducer(String id) throws JMSException {
        String from = TAG + id;
        Queue prod = senderSession.createQueue(from);
        return senderSession.createProducer(prod);
    }


    /**
     * Subscribe to topics meant for this user
     * @return MessageConsumer
     * @throws JMSException
     */
    private MessageConsumer createConsumer() throws JMSException {
        String to = TAG + userId;
        Queue cons = receiverSession.createQueue(to);
        return receiverSession.createConsumer(cons);
    }

    /**
     * Send a messag
     * @param producer
     * @param line
     * @throws JMSException
     */
    private void sendMessage(MessageProducer producer, String line) throws JMSException {

        TextMessage m = senderSession.createTextMessage(line);
        // add sender identity to message
        m.setStringProperty("sender", userId);
        producer.send(m);
    }

    /**
     * Close session and connection
     * @throws JMSException
     */
    public void closeSession() throws JMSException {
        if (senderSession != null) {
            senderSession.close();
        }
        if( receiverSession != null) {
            receiverSession.close();
        }
        if (connection != null) {
            connection.close();
        }
    }

    /**
     * Returns a thread object to handle receiving messages
     * @param consumer
     * @return Thread
     */
    private Thread getThread(MessageConsumer consumer) {

        Thread receivingThread = new Thread(() -> {
            try {

                while (!Thread.currentThread().isInterrupted()) {

                    // receive message with timeout
                    Message msg = consumer.receive(100); // 100ms timeout
                    if (msg instanceof TextMessage tm) {

                        // message contents
                        String sender = tm.getStringProperty("sender");
                        String body = tm.getText();

                        boolean isEmptyMessage = body.isBlank() || body.isEmpty();

                        // display only if not blocked and not empty
                        if (!isEmptyMessage) {
                            System.out.println("[" + sender + "]: " + body);
                        }
                        
                    }
                }
            } catch (javax.jms.JMSException e) {
                // Silently handle interruption - normal shutdown behavior
                if (!Thread.currentThread().isInterrupted()) {
                    System.err.println("Error receiving message: " + e.getMessage());
                }
            }
        });

        
        receivingThread.start();
        // we are returning this so we can interrupt it later
        return receivingThread;
    }


    /**
     * Prompt for user ID
     * @param sc
     */
    public void promptForUser(Scanner sc){

        System.out.print("Enter your user ID: ");
        setUserId(prompt(sc));
        // Instructions
        System.out.println("Welcome "+getUserId());
        printCommands();
    }

    private void printCommands() {
        System.out.println("- To exit the chat: exit");
    }

    /**
     * Prompt for correspondent ID
     * @param sc
     */
    public void promptForCorespondent(Scanner sc){

        System.out.print("Who do you want to chat with? ");
        String contact = prompt(sc);
        setCorespondent(contact);
        System.out.println("You can start with: " + getCorespondent());
    }

    /**
     * Generic prompt method prompts for whatever we need
     * @param sc Scanner object
     * @return String
     */
    private String prompt(Scanner sc) {

        String user = "";

        while (user.isEmpty()) {
            try {
                user = sc.next();

            } catch (Exception e) {
                System.err.println("Error reading correspondent ID: " + e.getMessage());
                return null;
            }
        }
        return user;
    }

    // Setters and getters
    // user
    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserId() {
        return userId;
    }

    // correspondent
    public String getCorespondent() {
        return corespondent;
    }

    public void setCorespondent(String corespondent) {
        this.corespondent = corespondent;
    }
}
