package sql.mirroring;

import hiro.yoshioka.sdh.DatabaseType;
import hiro.yoshioka.sql.engine.HsqlServerManager;
import hiro.yoshioka.sql.engine.Request;
import hiro.yoshioka.sql.engine.SQLOperationType;
import hiro.yoshioka.sql.engine.SQLServerThread;
import hiro.yoshioka.sql.params.ConnectionProperties;
import hiro.yoshioka.sql.params.ConnectionSettingBean;

import java.io.File;

import junit.framework.TestCase;

abstract public class AbsMirroringTest extends TestCase {
	static File macConnections = new File(
			"/Users/yonsama/tools/eclipse36/wk/WolfSQLParser/config/");
	static File winConnections = new File(
			"C:/tools/eclipse/wk/WolfSQLParser/config/");

	protected ConnectionProperties mirroring_from_con_properties = null;
	protected ConnectionProperties mirroring_to_con_properties = null;
	protected DatabaseType databaseTypeFrom;
	protected DatabaseType databaseTypeTo;
	protected ConnectionSettingBean bean = null;

	abstract void setUpMirroringConnection();

	private boolean hasHsqlDB() {
		return databaseTypeFrom.isHsql() || databaseTypeTo.isHsql();
	}

	@Override
	protected void setUp() throws Exception {
		super.setUp();

		if (hiro.yoshioka.util.Util.isWindowsOs()) {
			SQLServerThread.getSQLServer().init(winConnections);
		} else {
			SQLServerThread.getSQLServer().init(macConnections);
		}
		this.bean = SQLServerThread.getSQLServer().getConnectionSettingBean();
		setUpMirroringConnection();
		assertNotNull("Connection Properties must be not null.",
				mirroring_from_con_properties);
		assertNotNull("Connection Properties must be not null.",
				mirroring_to_con_properties);

		databaseTypeFrom = mirroring_from_con_properties.getDatabaseType();
		databaseTypeTo = mirroring_to_con_properties.getDatabaseType();

		if (hasHsqlDB()) {
			if (!HsqlServerManager.isRunning()) {
				HsqlServerManager.getInstance().start();
			}
		}
		Request request = new Request(SQLOperationType.CONNECT,
				mirroring_from_con_properties);
		assertTrue(String.format("connect to %s ...", databaseTypeFrom),
				SQLServerThread.runNowThisRequest(request));
		request = new Request(SQLOperationType.CONNECT,
				mirroring_to_con_properties);
		assertTrue(String.format("connect to %s ...", databaseTypeTo),
				SQLServerThread.runNowThisRequest(request));

	}

	@Override
	protected void tearDown() throws Exception {
		Request request = new Request(SQLOperationType.CLOSE,
				mirroring_from_con_properties);
		SQLServerThread.runNowThisRequest(request);
		request = new Request(SQLOperationType.CLOSE,
				mirroring_to_con_properties);
		SQLServerThread.runNowThisRequest(request);

		if (hasHsqlDB()) {
			if (HsqlServerManager.isRunning()) {
				HsqlServerManager.dispose();
			}
		}
		super.tearDown();
	}

}
