/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 Bull S.A.
 * Contact: jonas-team@objectweb.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$
 * --------------------------------------------------------------------------
 */


package org.objectweb.jonas.dbm;

import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;

import org.objectweb.jonas.common.Log;
import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * Wrapper on a PreparedStatement. This wrapper is used to track close method
 * in order to avoid closing the statement, and putting it instead in a pool.
 * @author durieuxp
 */
public class JStatement implements PreparedStatement {

    private boolean changed = false;
    private boolean opened;
    private boolean closing = false;

    /**
     * Physical PreparedStatement object on which the wrapper is.
     */
    private PreparedStatement ps;

    /**
     * Managed Connection the Statement belongs to
     */
    private JManagedConnection mc;

    private int hashCode;
    private String sql;
    private Logger logger = Log.getLogger(Log.JONAS_DBM_PREFIX + ".ps");

    public JStatement(PreparedStatement ps, JManagedConnection mc, String sql) {
        logger.log(BasicLevel.DEBUG, "constructor");
        this.ps = ps;
        this.mc = mc;
        this.sql = sql;
        hashCode = sql.hashCode();
        opened = true;
    }

    public String getSql() {
        return sql;
    }

    /**
     * @return hashcode of the object
     */
    public int hashCode() {
        return hashCode;
    }

    /**
     * @param stmt given statement for comparing it
     * @return true if given object is equals to this current object
     */
    public boolean equals(Object stmt) {
        if (stmt == null) {
            return false;
        }
        // different hashcode, cannot be equals
        if (this.hashCode != stmt.hashCode()) {
            return false;
        }

        // if got same hashcode, try to see if cast is ok.
        if (!(stmt instanceof JStatement)) {
            logger.log(BasicLevel.WARN, "Bad class:" + stmt);
            return false;
        }
        JStatement psw = (JStatement) stmt;
        if (sql == null && psw.getSql() != null) {
            return false;
        }
        if (sql != null && !sql.equals(psw.getSql())) {
            return false;
        }
        try {
            if (psw.getResultSetType() != getResultSetType()) {
                return false;
            }
            if (psw.getResultSetConcurrency() != getResultSetConcurrency()) {
                return false;
            }
        } catch (SQLException e) {
            logger.log(BasicLevel.WARN, "Cannot compare statements:" + e);
            return false;
        }
        logger.log(BasicLevel.DEBUG, "Found");
        return true;
    }

    /**
     * Force a close on the Prepare Statement.
     * Usually, it's the caller that did not close it explicitly
     * @return true if it was open
     */
    public boolean forceClose() {
        if (opened) {
            logger.log(BasicLevel.WARN, "Statements should be closed explicitly.");
            opened = false;
            return true;
        } else {
            return false;
        }
    }

    public void reuse() throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.clearParameters();
        ps.clearWarnings();
        opened = true;
        if (changed) {
            logger.log(BasicLevel.DEBUG, "changed");
            ps.clearBatch();
            ps.setFetchDirection(ResultSet.FETCH_FORWARD);
            ps.setMaxFieldSize(0);
            ps.setMaxRows(0);
            ps.setQueryTimeout(0);
            changed = false;
        }
    }

    public boolean isClosed() {
        return ! opened && ! closing;
    }

    /**
     * Physically close this Statement
     * @throws SQLException
     */
    public void forget() {
        logger.log(BasicLevel.DEBUG, "");
        try {
            ps.close();
        } catch (SQLException e) {
            logger.log(BasicLevel.ERROR, "Cannot close the PreparedStatement:" + e);
        }
    }

    // ------------------------------------------------------------------
    // PreparedStatement implementation.
    // Most of the methods are just redirected on the PreparedStatement.
    // ------------------------------------------------------------------

    public int executeUpdate() throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        return ps.executeUpdate();
    }

    public void addBatch() throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        changed = true;
        ps.addBatch();
    }

    public void clearParameters() throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.clearParameters();
    }

    public boolean execute() throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        return ps.execute();
    }

    public void setByte(int parameterIndex, byte x) throws SQLException {
        ps.setByte(parameterIndex, x);
    }

    public void setDouble(int parameterIndex, double x) throws SQLException {
        ps.setDouble(parameterIndex, x);
    }

    public void setFloat(int parameterIndex, float x) throws SQLException {
        ps.setFloat(parameterIndex, x);
    }

    public void setInt(int parameterIndex, int x) throws SQLException {
        ps.setInt(parameterIndex, x);
    }

    public void setNull(int parameterIndex, int sqlType) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setNull(parameterIndex, sqlType);
    }

    public void setLong(int parameterIndex, long x) throws SQLException {
        ps.setLong(parameterIndex, x);
    }

    public void setShort(int parameterIndex, short x) throws SQLException {
        ps.setShort(parameterIndex, x);
    }

    public void setBoolean(int parameterIndex, boolean x) throws SQLException {
        ps.setBoolean(parameterIndex, x);
    }

    public void setBytes(int parameterIndex, byte[] x) throws SQLException {
        ps.setBytes(parameterIndex, x);
    }

    public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setAsciiStream(parameterIndex, x, length);
    }

    public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setBinaryStream(parameterIndex, x, length);
    }

    public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setUnicodeStream(parameterIndex, x, length);
    }

    public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setCharacterStream(parameterIndex, reader, length);
    }

    public void setObject(int parameterIndex, Object x) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setObject(parameterIndex, x);
    }

    public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setObject(parameterIndex, x, targetSqlType);
    }

    public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setObject(parameterIndex, x, targetSqlType, scale);
    }

    public void setNull(int paramIndex, int sqlType, String typeName) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setNull(paramIndex, sqlType, typeName);
    }

    public void setString(int parameterIndex, String x) throws SQLException {
        ps.setString(parameterIndex, x);
    }

    public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setBigDecimal(parameterIndex, x);
    }

    public void setURL(int parameterIndex, URL x) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setURL(parameterIndex, x);
    }

    public void setArray(int i, Array x) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setArray(i, x);
    }

    public void setBlob(int i, Blob x) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setBlob(i, x);
    }

    public void setClob(int i, Clob x) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setClob(i, x);
    }

    public void setDate(int parameterIndex, Date x) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setDate(parameterIndex, x);
    }

    public ParameterMetaData getParameterMetaData() throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        return ps.getParameterMetaData();
    }

    public void setRef(int i, Ref x) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setRef(i, x);
    }

    public ResultSet executeQuery() throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        return ps.executeQuery();
    }

    public ResultSetMetaData getMetaData() throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        return ps.getMetaData();
    }

    public void setTime(int parameterIndex, Time x) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setTime(parameterIndex, x);
    }

    public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setTimestamp(parameterIndex, x);
    }

    public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setDate(parameterIndex, x, cal);
    }

    public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setTime(parameterIndex, x, cal);
    }

    public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setTimestamp(parameterIndex, x, cal);
    }

    public int getFetchDirection() throws SQLException {
        return ps.getFetchDirection();
    }

    public int getFetchSize() throws SQLException {
        return ps.getFetchSize();
    }

    public int getMaxFieldSize() throws SQLException {
        return ps.getMaxFieldSize();
    }

    public int getMaxRows() throws SQLException {
        return ps.getMaxRows();
    }

    public int getQueryTimeout() throws SQLException {
        return ps.getQueryTimeout();
    }

    public int getResultSetConcurrency() throws SQLException {
        return ps.getResultSetConcurrency();
    }

    public int getResultSetHoldability() throws SQLException {
        return ps.getResultSetHoldability();
    }

    public int getResultSetType() throws SQLException {
        return ps.getResultSetType();
    }

    public int getUpdateCount() throws SQLException {
        return ps.getUpdateCount();
    }

    public void cancel() throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.cancel();
    }

    public void clearBatch() throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.clearBatch();
    }

    public void clearWarnings() throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.clearWarnings();
    }

    public void close() throws SQLException {
        if (! opened) {
            logger.log(BasicLevel.DEBUG, "Statement already closed");
            return;
        }
        logger.log(BasicLevel.DEBUG, "");
        opened = false;
        closing  = true;
        mc.notifyPsClose(this);
        closing = false;
    }

    public boolean getMoreResults() throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        return ps.getMoreResults();
    }

    public int[] executeBatch() throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        return ps.executeBatch();
    }

    public void setFetchDirection(int direction) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        changed = true;
        ps.setFetchDirection(direction);
    }

    public void setFetchSize(int rows) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        changed = true;
        ps.setFetchSize(rows);
    }

    public void setMaxFieldSize(int max) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        changed = true;
        ps.setMaxFieldSize(max);
    }

    public void setMaxRows(int max) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        changed = true;
        ps.setMaxRows(max);
    }

    public void setQueryTimeout(int seconds) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        changed = true;
        ps.setQueryTimeout(seconds);
    }

    public boolean getMoreResults(int current) throws SQLException {
        return ps.getMoreResults(current);
    }

    public void setEscapeProcessing(boolean enable) throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        ps.setEscapeProcessing(enable);
    }

    public int executeUpdate(String sql) throws SQLException {
        logger.log(BasicLevel.DEBUG, sql);
        return ps.executeUpdate(sql);
    }

    public void addBatch(String sql) throws SQLException {
        logger.log(BasicLevel.DEBUG, sql);
        changed = true;
        ps.addBatch(sql);
    }

    public void setCursorName(String name) throws SQLException {
        logger.log(BasicLevel.DEBUG, name);
        ps.setCursorName(name);
    }

    public boolean execute(String sql) throws SQLException {
        logger.log(BasicLevel.DEBUG, sql);
        changed = true;
        return ps.execute(sql);
    }

    public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
        logger.log(BasicLevel.DEBUG, sql);
        changed = true;
        return ps.executeUpdate(sql, autoGeneratedKeys);
    }

    public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
        logger.log(BasicLevel.DEBUG, sql);
        changed = true;
        return ps.execute(sql, autoGeneratedKeys);
    }

    public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
        logger.log(BasicLevel.DEBUG, sql);
        changed = true;
        return ps.executeUpdate(sql, columnIndexes);
    }

    public boolean execute(String sql, int[] columnIndexes) throws SQLException {
        logger.log(BasicLevel.DEBUG, sql);
        changed = true;
        return ps.execute(sql, columnIndexes);
    }

    public Connection getConnection() throws SQLException {
        return ps.getConnection();
    }

    public ResultSet getGeneratedKeys() throws SQLException {
        return ps.getGeneratedKeys();
    }

    public ResultSet getResultSet() throws SQLException {
        return ps.getResultSet();
    }

    public SQLWarning getWarnings() throws SQLException {
        return ps.getWarnings();
    }

    public int executeUpdate(String sql, String[] columnNames) throws SQLException {
        logger.log(BasicLevel.DEBUG, sql);
        return ps.executeUpdate(sql, columnNames);
    }

    public boolean execute(String sql, String[] columnNames) throws SQLException {
        logger.log(BasicLevel.DEBUG, sql);
        return ps.execute(sql, columnNames);
    }

    public ResultSet executeQuery(String sql) throws SQLException {
        logger.log(BasicLevel.DEBUG, sql);
        return ps.executeQuery(sql);
    }

}