/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2004 Bull S.A.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: HsqlDBServiceImpl.java 21566 2011-08-08 12:28:12Z cazauxj $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.db.hsqldb;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Iterator;
import java.util.List;

import org.hsqldb.Server;
import org.hsqldb.ServerConstants;
import org.objectweb.util.monolog.api.BasicLevel;
import org.ow2.jonas.db.DBService;
import org.ow2.jonas.db.base.AbsDBServiceImpl;
import org.ow2.jonas.db.base.AbsDBServiceImplMBean;
import org.ow2.jonas.db.base.User;
import org.ow2.jonas.service.ServiceException;

/**
 * Embeds the HSQL database in JOnAS.
 * @author Florent Benoit
 */
public class HsqlDBServiceImpl extends AbsDBServiceImpl implements DBService, AbsDBServiceImplMBean {

    /**
     * List of users.
     */
    private List<User> users = null;

    /**
     * Name of database.
     */
    private String databaseName = null;

    /**
     * Default port number.
     */
    private static final String DEFAULT_PORT = "9001";

    /**
     * Sleep value.
     */
    private static final int SLEEP_VALUE = 100;

    /**
     * Max retry number.
     */
    private static final int MAX_RETRY_NB = 20;

    /**
     * port number used.
     */
    private String portNumber = null;

    /**
     * HsqlDB server.
     */
    private Server server = null;

    /**
     * Create a database with the specified arguments.
     * @param users user/password (separated by a ":")
     * @param databaseName name of the database
     * @param portNumber port number of the database
     */

    @Override
    protected void initServer(final List<User> users, final String databaseName, final String portNumber) throws ServiceException {
        this.users = users;
        if (portNumber != null) {
            this.portNumber = portNumber;
        } else {
            this.portNumber = DEFAULT_PORT;
        }
        this.databaseName = databaseName;

        server = new Server();
        // Remove all traces if level != DEBUG
        if (!getLogger().isLoggable(BasicLevel.DEBUG)) {
            server.setLogWriter(null);
            server.setErrWriter(null);
            server.setSilent(true);
            server.setTrace(false);
            server.setLogWriter(null);
        } else {
            // Enable all traces : verbose mode (as user needs DEBUG)
            server.setSilent(false);
            server.setTrace(true);
        }

        String baseDir = getServerProperties().getWorkDirectory() + File.separator + "hsqldb" + File.separator + databaseName;
        String pString = "";
        if (portNumber != null) {
            pString = ";port=" + portNumber;
        }
        String serverProps = "database.0=" + baseDir + ";dbname.0=" + databaseName + pString;
        server.putPropertiesFromString(serverProps);

    }

    /**
     * Start the service.
     * @throws ServiceException if the startup failed.
     */
    @Override
    protected void doStart() throws ServiceException {
        super.doStart();
        if (getLogger().isLoggable(BasicLevel.INFO)) {
            getLogger().log(BasicLevel.INFO, "Starting " + server.getProductName() + " "
                                             + server.getProductVersion() + " on port " + portNumber);
        }
        if (getLogger().isLoggable(BasicLevel.DEBUG)) {
            getLogger().log(BasicLevel.DEBUG, "serverState=" + server.getState());
        }
        server.start();

        // Wait the start
        int retryNb = 0;
        while (server.getState() != ServerConstants.SERVER_STATE_ONLINE) {
            try {
                Thread.sleep(SLEEP_VALUE);
            } catch (InterruptedException ie) {
                getLogger().log(BasicLevel.ERROR, "Can't wait that the service is online", ie);
            }
            // Error if server state is "SHUTDOWN" during a long period
            // Maybe strange but 'SHUTDOWN' state seems to be an intermediate state during startup
            retryNb++;
            if (server.getState() == ServerConstants.SERVER_STATE_SHUTDOWN && retryNb >= MAX_RETRY_NB) {
                    Throwable t = server.getServerError();
                    throw new ServiceException("The server was shutdown :", t);
            }
            if (getLogger().isLoggable(BasicLevel.DEBUG)) {
                getLogger().log(BasicLevel.DEBUG, "retry=" + retryNb + ", serverState=" + server.getState());
            }
        }

        getLogger().log(BasicLevel.INFO, server.getProductName() + " started.");
        Connection conn = null;
        Statement st = null;
        try {

            Class.forName("org.hsqldb.jdbcDriver");
            conn = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost:" + portNumber + "/" + databaseName, "sa",
                    "");
            st = conn.createStatement();
        } catch (Exception e) {
            throw new ServiceException("Cannot access to HSQL", e);
        }

        // Drop users before recreating it
        User user = null;
        String userName = null;
        String password = null;
        ResultSet rs = null;
        for (Iterator<User> it = users.iterator(); it.hasNext();) {
            user = it.next();
            try {
                password = user.getPassword();
                userName = user.getUserName();
                getLogger().log(BasicLevel.INFO,
                                "Dropping and adding user '" + userName
                                + "' with password '" + password + "'.");
                try {
                    rs = st.executeQuery("DROP USER " + userName);
                } catch (Exception ee) {
                    if (getLogger().isLoggable(BasicLevel.DEBUG)) {
                        getLogger().log(BasicLevel.DEBUG, "User '" + userName + "' doesn't exists", ee);
                    }
                }
                rs = st.executeQuery("Create USER " + userName + " PASSWORD " + password + " ADMIN");
                rs.close();
            } catch (Exception e) {
                getLogger().log(BasicLevel.ERROR, "Error while creating/adding user", e);
            }

        }

        try {
            st.close();
        } catch (Exception e) {
            if (getLogger().isLoggable(BasicLevel.DEBUG)) {
                getLogger().log(BasicLevel.DEBUG, "Error while closing statement object", e);
            }
        }

    }

    /**
     * Stop the service.
     * @throws ServiceException if the stop failed.
     */
    @Override
    protected void doStop() throws ServiceException {
        super.doStop();

        server.shutdown();
        getLogger().log(BasicLevel.INFO, server.getProductName() + " stopped.");

    }

}
