package vs;

import java.util.Random;

import jakarta.jms.Connection;
import jakarta.jms.ConnectionFactory;
import jakarta.jms.JMSException;
import jakarta.jms.Message;
import jakarta.jms.MessageConsumer;
import jakarta.jms.MessageListener;
import jakarta.jms.MessageProducer;
import jakarta.jms.Queue;
import jakarta.jms.Session;
import jakarta.jms.TextMessage;
import jakarta.jms.Topic;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class PasswordCandidateGenerator implements MessageListener {
	private Connection connection;
	private Session session;
	private MessageProducer producer;
	private MessageConsumer consumer;
	private Random random;
	private boolean stopped = false;

	public PasswordCandidateGenerator() throws NamingException, JMSException {
		this.random = new Random();
		Context ctx = new InitialContext();
		ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory");
		this.connection = factory.createConnection();
		this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Queue taskQueue = (Queue) ctx.lookup(Conf.TASK_QUEUE);
		this.producer = this.session.createProducer(taskQueue);
		Topic successTopic = (Topic) ctx.lookup(Conf.SUCCESS_TOPIC);
		this.consumer = this.session.createConsumer(successTopic);
		this.consumer.setMessageListener(this);
		this.connection.start();
	}

	@Override
	public void onMessage(Message message) {
		this.stopped = true;
		System.out.println("Password gefunden. PasswordCandidateGenerator wird gestoppt.");
	}

	public void sendMessage(String text) throws JMSException {
		TextMessage message = this.session.createTextMessage();
		message.setText(text);
		this.producer.send(message);
	}

	public String generatePasswordCandidate(int length) {
		StringBuilder buffer = new StringBuilder(length);
		final int letterA = 97;
		final int letterZ = 122;
		for (int i = 0; i < length; i++) {
			buffer.append((char) (letterA + (int) (this.random.nextFloat() * ((letterZ - letterA) + 1))));
		}
		return buffer.toString();
	}

	public static void main(String[] args) {
		PasswordCandidateGenerator node = null;
		try {
			node = new PasswordCandidateGenerator();
			while (!node.stopped) {
				node.sendMessage(node.generatePasswordCandidate(8));
			}
		} catch (NamingException | JMSException e) {
			System.err.println(e);
		} finally {
			try {
				if ((node != null) && (node.producer != null)) {
					node.producer.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);
			}
		}
	}

}
