/*
 * Copyright 2004 The original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ca.polymtl.larim.schaman.persistence;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.WebApplicationContext;


/**
 * Description of HsqlServer.
 * 
 * @version CVS $Id: HsqlServer.java 3 2004-10-18 20:56:13Z ugo $
 */
public class HsqlServer implements Runnable, ApplicationContextAware {

    /** Arguments for running the server */
    private String arguments[] = new String[10];
    private boolean trace = false;
    private boolean silent = true;
    private int port = 9002;
    private Thread server;

    public void start() {
        server = new Thread(this);
        server.setPriority(Thread.currentThread().getPriority());
        server.setDaemon(true);
        server.setName("hsqldb server");
        server.start();
    }
    
    public void stop() {
        try {
            Connection connection = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost:" + this.port, "sa", "");
            Statement statement = connection.createStatement();
            statement.executeQuery("SHUTDOWN");
            try {
                connection.close();
            } catch (SQLException e) {
                /* FIXME
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("Shutting down HSQLDB: Ignoring exception: " + e);
                }
                */
            }
        } catch (Exception e){
            /* FIXME getLogger().error("Error while shutting down HSQLDB", e); */
        }
    }
    
    /* (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    public void run() {
        arguments[0] = "-port";
        arguments[1] = new Integer(this.getPort()).toString();
        arguments[2] = "-silent";
        arguments[3] = new Boolean(this.isSilent()).toString();
        arguments[4] = "-trace";
        arguments[5] = new Boolean(this.isTrace()).toString();
        arguments[6] = "-no_system_exit";
        arguments[7] = "true";
        // FIXME: log
        System.err.println("Starting HSQL server...");
        org.hsqldb.Server.main(arguments);
    }

    /**
     * @return Returns the port.
     */
    public int getPort() {
        return port;
    }
    
    /**
     * @param port The port to set.
     */
    public void setPort(int port) {
        this.port = port;
    }
    
    /**
     * @return Returns the silent.
     */
    public boolean isSilent() {
        return silent;
    }
    
    /**
     * @param silent The silent to set.
     */
    public void setSilent(boolean silent) {
        this.silent = silent;
    }
    
    /**
     * @return Returns the trace.
     */
    public boolean isTrace() {
        return trace;
    }
    
    /**
     * @param trace The trace to set.
     */
    public void setTrace(boolean trace) {
        this.trace = trace;
    }

    /* (non-Javadoc)
     * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
     */
    public void setApplicationContext(ApplicationContext appCtx) throws BeansException {
        try {
            WebApplicationContext webCtx = (WebApplicationContext) appCtx;
            String dbPath = webCtx.getServletContext().getRealPath("/WEB-INF/db");
            arguments[8] = "-database";
            arguments[9] = new File(dbPath).getCanonicalPath();
            arguments[9] += File.separator + "schamandb";
        }
        catch (ClassCastException ex) {
            // FIXME: this is not a web app. log this
            throw ex;
        } catch (IOException ex) {
            // FIXME
            throw new RuntimeException(ex.getMessage(), ex);
        }
        
    }
    
	/**
	 * @return Returns the server thread.
	 */
	public Thread getServer() {
		return server;
	}
}
