package hiro.yoshioka.sql.engine;

import hiro.yoshioka.util.StringUtil;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hsqldb.Server;

public class HsqlServerManager {
	static Log log = LogFactory.getLog(HsqlServerManager.class);
	private static HsqlServerManager single;
	private static Server server = new Server();
	static {
		PrintWriter normal = new PrintWriter(new MyWriter(true));
		server.setLogWriter(normal);
		PrintWriter err = new PrintWriter(new MyWriter(false));
		server.setErrWriter(err);
	}

	static class MyWriter extends Writer {
		public boolean isNormal;

		public MyWriter(boolean isNormal) {
			this.isNormal = isNormal;
		}

		@Override
		public void close() throws IOException {
		}

		@Override
		public void flush() throws IOException {
		}

		@Override
		public void write(char[] cbuf, int off, int len) throws IOException {
			String target = new String(cbuf, off, len).trim();
			if (StringUtil.isEmpty(target)) {
				return;
			}
			if (isNormal) {
				log.info(target);
			} else {
				log.warn(target);
			}
		}
	}

	private HsqlServerManager() {
	}

	public static HsqlServerManager getInstance() {
		if (single == null) {
			single = new HsqlServerManager();
		}
		return single;
	}

	public void start() {
		if (!isRunning()) {
			log.info("exec start");
			server.setDatabaseName(0, "hsql_db_yon");
			server.setDatabasePath(0, "file:hsql_db_yon");
			server.setPort(9003);
			server.setSilent(true);
			server.start();
		}
	}

	public void stop() {
		log.info("exec stop");
		shutDownServer();
	}

	public static boolean isRunning() {
		if (server == null) {
			return false;
		}
		return server.getState() <= 4;
	}

	public static void dispose() {
		shutDownServer();
	}

	private static void shutDownServer() {
		try {
			if (server != null) {
				server.shutdown();
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

}