/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2010 Bull S.A.S.
 * 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: JConnection.java 21566 2011-08-08 12:28:12Z cazauxj $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.dbm.internal.cm;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

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

/**
 * This is a wrapper on the logical Connection.
 * Only close and setAutoCommit have a special treatment.
 * @author durieuxp
 */
public class JConnection implements InvocationHandler {

    static private Logger logger = Log.getLogger(Log.JONAS_DBM_PREFIX + ".con");


    /**
     * JDBC connection provided by the DriverManager.
     */
    private Connection physicalConnection = null;

    /**
     * XA connection which receive events.
     */
    private JManagedConnection xaConnection = null;


    protected boolean checkclose = true;

    /**
     * Buils a Connection (viewed by the user) which rely on a Managed
     * connection and a physical connection.
     * @param xaConnection the XA connection.
     * @param physicalConnection the connection to the database.
     */
    public JConnection(final JManagedConnection xaConnection, final Connection physicalConnection) {
        this.xaConnection = xaConnection;
        this.physicalConnection = physicalConnection;
    }

    /**
     * Gets the physical connection to the database.
     * @return physical connection to the database
     */
    public Connection getConnection() {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }
        return physicalConnection;
    }

    /**
     * @return true if the connection to the database is closed or not.
     * @throws SQLException if a database access error occurs
     */
    public boolean isPhysicallyClosed() throws SQLException {
        logger.log(BasicLevel.DEBUG, "");
        return physicalConnection.isClosed();
    }

    /**
     * Processes a method invocation on a proxy instance and returns the result.
     * This method will be invoked on an invocation handler when a method is
     * invoked on a proxy instance that it is associated with.
     * @param proxy the proxy instance that the method was invoked on
     * @param method the <code>Method</code> instance corresponding to the
     *        interface method invoked on the proxy instance.
     * @param args an array of objects containing the values of the arguments
     *        passed in the method invocation on the proxy instance, or
     *        <code>null</code> if interface method takes no arguments.
     * @return the value to return from the method invocation on the proxy
     *         instance.
     * @throws Throwable the exception to throw from the method invocation on
     *         the proxy instance. The exception's type must be assignable
     *         either to any of the exception types declared in the
     *         <code>throws</code> clause of the interface method or to the
     *         unchecked exception types <code>java.lang.RuntimeException</code>
     *         or <code>java.lang.Error</code>. If a checked exception is
     *         thrown by this method that is not assignable to any of the
     *         exception types declared in the <code>throws</code> clause of
     *         the interface method, then an UndeclaredThrowableException
     *         containing the exception that was thrown by this method will be
     *         thrown by the method invocation on the proxy instance.
     */
    public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {

        // Methods on the Object.class are not send on the connection impl
        if (method.getDeclaringClass().getName().equals("java.lang.Object")) {
            return handleObjectMethods(method, args);
        }

        // Methods that are part of the IConnection interface
        if ("getConnection".equals(method.getName())) {
            return getConnection();
        } else if ("isClosed".equals(method.getName())) {
            return isClosed();
        } else if ("isPhysicallyClosed".equals(method.getName())) {
            return Boolean.valueOf(isPhysicallyClosed());
        } else if ("setCheckClose".equals(method.getName())) {
            setCheckClose((Boolean) args[0]);
            return null;
        } else if ("close".equals(method.getName())) {
            xaConnection.notifyClose();
            return null;
        } else if ("prepareStatement".equals(method.getName()) && method.getParameterTypes().length == 1) {
            // Use the xaConnection Object (which allow to have the preparedstatement pool) but only for method with SQL
            try {
                return xaConnection.prepareStatement((String) args[0]);
            } catch (SQLException e) {
                    if (logger.isLoggable(BasicLevel.DEBUG)) {
                        logger.log(BasicLevel.DEBUG, "Exception while calling method '" + method + "' on object '"
                            +  xaConnection + "'.", e);
                    }
                    xaConnection.notifyError(e);
                    throw e;
            }
        } else {

            if (!(method.getName().startsWith("get") || method.getName().startsWith("set"))) {
                if (checkclose && isClosed()) {
                    logger.log(BasicLevel.ERROR, "Cannot work with a closed Connection");
                    throw new SQLException("Cannot work with a closed Connection");
                }
            }
            // Else delegate to the physicalConnection object
            try {
                Class<?> physicalConnectionClass = physicalConnection.getClass();
                Class<?> methodClass = method.getDeclaringClass();
                if (methodClass.isAssignableFrom(physicalConnectionClass)) {
                    return method.invoke(physicalConnection, args);
                } else {
                    throw new IllegalArgumentException("Proxy error: the physical connection (class: "
                        + physicalConnectionClass.getName() + ") cannot be cast to a " + methodClass.getName());
                }
            } catch (InvocationTargetException e) {
                // Check if it is an SQLException
                Throwable targetException = e.getTargetException();
                if (targetException instanceof SQLException) {
                    if (logger.isLoggable(BasicLevel.DEBUG)) {
                        logger.log(BasicLevel.DEBUG, "Exception while calling method '" + method + "' on object '"
                            +  physicalConnection + "'.");
                    }
                    xaConnection.notifyError((SQLException) targetException);
                }
                // Rethrow Exception
                throw targetException;
            }

        }
    }


    /**
     * Manages all methods of java.lang.Object class.
     * @param method the <code>Method</code> instance corresponding to the
     *        interface method invoked on the proxy instance. The declaring
     *        class of the <code>Method</code> object will be the interface
     *        that the method was declared in, which may be a superinterface of
     *        the proxy interface that the proxy class inherits the method
     *        through.
     * @param args an array of objects containing the values of the arguments
     *        passed in the method invocation on the proxy instance
     * @return the value of the called method.
     */
    protected Object handleObjectMethods(final Method method, final Object[] args) {
        String methodName = method.getName();

        if (methodName.equals("equals")) {
            // equals with a proxy
            if (Proxy.isProxyClass(args[0].getClass())) {
                return this.equals(Proxy.getInvocationHandler(args[0]));
            }
            return Boolean.valueOf(this.equals(args[0]));
        } else if (methodName.equals("toString")) {
            return this.toString();
        } else if (methodName.equals("hashCode")) {
            return Integer.valueOf(this.hashCode());
        } else {
            throw new IllegalStateException("Method '" + methodName + "' is not present on Object.class.");
        }
    }

    public void setCheckClose(final boolean cc) {
        checkclose = cc;
    }

    public boolean isClosed() throws SQLException {
        return xaConnection.isClosed();
    }
}
