package omq.test.supervisor;

import java.util.Properties;

import omq.common.broker.Broker;
import omq.common.util.ParameterQueue;
import omq.supervisor.OmqSettings;
import omq.supervisor.Supervisor;
import omq.supervisor.SupervisorImpl;

import org.junit.BeforeClass;
import org.junit.Test;

public class SleepTest {
	private static String brokerSet = "broker";

	@BeforeClass
	public static void Server() throws Exception {
		System.out.println("hola");
		Properties env1 = new Properties();
		env1.setProperty(ParameterQueue.USER_NAME, "guest");
		env1.setProperty(ParameterQueue.USER_PASS, "guest");

		// Get host info of rabbimq (where it is)
		env1.setProperty(ParameterQueue.RABBIT_HOST, "127.0.0.1");
		env1.setProperty(ParameterQueue.RABBIT_PORT, "5672");
		env1.setProperty(ParameterQueue.MIN_POOL_THREADS, "1");
		env1.setProperty(ParameterQueue.MAX_POOL_THREADS, "1");

		Broker broker = new Broker(env1);

		Properties env2 = new Properties();
		env2.setProperty(ParameterQueue.USER_NAME, "guest");
		env2.setProperty(ParameterQueue.USER_PASS, "guest");

		// Get host info of rabbimq (where it is)
		env2.setProperty(ParameterQueue.RABBIT_HOST, "127.0.0.1");
		env2.setProperty(ParameterQueue.RABBIT_PORT, "5672");
		env2.setProperty(ParameterQueue.MIN_POOL_THREADS, "1");
		env2.setProperty(ParameterQueue.MAX_POOL_THREADS, "1");

		Broker broker2 = new Broker(env2);

		// Set supervisor
		SupervisorImpl supervisor = new SupervisorImpl(brokerSet, 500);
		broker.bind("supervisor", supervisor);
		Thread t = new Thread(supervisor);
		t.start();

		broker.setSupervisor("supervisor", brokerSet, "b1");
		broker2.setSupervisor("supervisor", brokerSet, "b2");
	}

	@Test
	public void test() throws Exception {
		Properties env = new Properties();
		env.setProperty(ParameterQueue.USER_NAME, "guest");
		env.setProperty(ParameterQueue.USER_PASS, "guest");

		// Get host info of rabbimq (where it is)
		env.setProperty(ParameterQueue.RABBIT_HOST, "127.0.0.1");
		env.setProperty(ParameterQueue.RABBIT_PORT, "5672");

		Broker broker = new Broker(env);
		Supervisor supervisor = broker.lookup("supervisor", Supervisor.class);

		OmqSettings settings = new OmqSettings("sleep", SleepImpl.class.getName(), env, 1, 20, 20);
		supervisor.spawnObject(settings);

		Sleep sleep = broker.lookup("sleep", Sleep.class);

		for (int i = 0; i < 10; i++) {
			sleep.sleep();
		}
		Thread.sleep(5000);
		for (int i = 0; i < 20; i++) {
			sleep.sleep();
		}
		Thread.sleep(18000);
		for (int i = 0; i < 20; i++) {
			sleep.sleep();
		}

		Thread.sleep(100000);
	}

}
