package omq.supervisor;

import java.util.Map;
import java.util.Set;

import com.rabbitmq.client.AMQP.Queue.DeclareOk;
import com.rabbitmq.client.Channel;

public class SupervisorThread extends Thread {

	private long sleep;
	private SupervisorImpl supervisor;
	private Map<String, OmqSettings> objectSettings;

	public SupervisorThread(SupervisorImpl supervisor, long sleep) {
		this.sleep = sleep;
		this.supervisor = supervisor;
		this.objectSettings = supervisor.getObjectSettings();
	}

	@Override
	public void run() {
		while (true) {
			try {
				Set<String> keys = objectSettings.keySet();
				for (String reference : keys) {
					checkObject(reference);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				Thread.sleep(sleep);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void checkObject(String reference) throws Exception {
		OmqSettings settings = objectSettings.get(reference);

		int minObjects = settings.getMinNumberObjects();
		int maxMessages = settings.getMaxNumQueued();
		int minMessages = settings.getMinNumQueued();

		// TODO treure merda...
		Channel channel = supervisor.getBroker().getChannel();
		DeclareOk dok = channel.queueDeclarePassive(reference);

		int numConsumers = dok.getConsumerCount();
		int numMessages = dok.getMessageCount();

		System.out.println("Num Consumers: " + numConsumers + ", num Messages: " + numMessages);

		if (maxMessages < numMessages || minObjects < numConsumers) {
			System.out.println("SPAWN TIME!!");
			supervisor.spawnObject(settings);
			// spawn:
			// pregunta a tots i qui no té l'objecte li poses
		} else if (numMessages < minMessages && minObjects > numConsumers) {
			supervisor.unbindObject(settings);
			// delete:
			// pregunta a tots i qui té l'objecte li treus
		}
	}
}
