package jp.co.denso.fa.jmscaosql.jms;

import java.io.FileOutputStream;
import java.util.List;
import java.util.Properties;

import jp.co.denso.fa.jmscaosql.JmsCaoSQLRmiClient;
import junit.framework.TestCase;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;

@ContextConfiguration
public class JmsCaoSQLRmiClientTest extends TestCase {

	JmsCaoSQLRmiClient client;
	ClassPathXmlApplicationContext context;

	public JmsCaoSQLRmiClientTest(String name) {
		super(name);
	}

	/* (非 Javadoc)
	 * @see junit.framework.TestCase#setUp()
	 */
	@Override
	protected void setUp() throws Exception {
		super.setUp();
		context = new ClassPathXmlApplicationContext("JmsCaoSQLTest-context.xml");
	}

	/* (非 Javadoc)
	 * @see junit.framework.TestCase#tearDown()
	 */
	@Override
	protected void tearDown() throws Exception {
		super.tearDown();
		if (context != null) {
			context.close();
		}
	}

	/**
	 * 同期状態でスレッドを待機します。
	 *
	 * @param time 待機時間(ミリ秒)
	 */
	protected synchronized void sleep(int time) {
		try {
			wait(time);
		} catch (InterruptedException e) {
		}
	}

	private void updateTarget(String targetCtlrName) throws Exception {
		String basepath = System.getProperty("user.dir");
		Properties prop = new Properties();
		prop.setProperty("event.listen.target", targetCtlrName);
		prop.store(new FileOutputStream(basepath + "/target/test-classes/jmscaosql.properties"), "Controller name to be published");
	}

	public void testStartStop() throws Exception {
		client = (JmsCaoSQLRmiClient)context.getBean("rmiClient");
		List<String> errors = client.init();
		assertTrue(errors.isEmpty());
		sleep(10000);
		assertTrue(client.isRunning());
		client.stop();
		assertFalse(client.isRunning());
	}

	public void testBlankProperties() throws Exception {
		updateTarget("");

		client = (JmsCaoSQLRmiClient)context.getBean("rmiClient");
		List<String> errors = client.init();
		assertTrue(errors.isEmpty());
		sleep(10000);
		assertTrue(client.isRunning());
		client.stop();
		assertFalse(client.isRunning());
	}

	public void testValidProperties() throws Exception {
		updateTarget("Controller3");

		client = (JmsCaoSQLRmiClient)context.getBean("rmiClient");
		List<String> errors = client.init();
		assertTrue(errors.isEmpty());
		sleep(10000);
		assertTrue(client.isRunning());
		client.stop();
		assertFalse(client.isRunning());
	}

	public void testInvalidProperties() throws Exception {
		updateTarget("Controller2");

		client = (JmsCaoSQLRmiClient)context.getBean("rmiClient");
		List<String> errors = client.init();
		assertTrue(errors.isEmpty());
		sleep(10000);
		assertTrue(client.isRunning());
		client.stop();
		assertFalse(client.isRunning());
	}
}
