/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 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
 *
 * Initial developer(s): Eric HARDESTY
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.ee.jdbc;

import java.sql.SQLException;

import javax.resource.spi.ConnectionEvent;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;

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

/**
 * This is an implementation of XAResource used for transaction mgmt
 * with a JDBC driver.  The standard JDBC drivers don't support real
 * XA, so the prepare will just return OK and work will be done in the
 * commit/rollback.
 */
public class XAResourceImpl implements XAResource {

    // Current Xid
    private Xid currentXid = null;

    // Is a xa transaction started ?
    boolean started = false;
    boolean ended = true;

    protected ManagedConnectionImpl mc = null;
    private XAResource xares = null;

    protected Logger xalog = null;

    /**
     * XAResourceImpl constructor
     * @param mc ManagedConnectionImpl used with this object
     * @param xares XAResource from DB if supported
     */
    public XAResourceImpl(ManagedConnectionImpl mc, XAResource xares) {
        this.mc = mc;
        this.xares = xares;
        xalog = Log.getLoggerFactory().getLogger("org.ow2.jonas.ee.jdbc.xa");
        if (xalog.isLoggable(BasicLevel.DEBUG)) {
            xalog.log(BasicLevel.DEBUG, "mc=" + mc);
        }
    }

    /**
     * Commit the global transaction specified by xid.
     */
    public void commit(Xid xid, boolean onePhase) throws XAException {
        if (xalog.isLoggable(BasicLevel.DEBUG)) {
            xalog.log(BasicLevel.DEBUG, "mc=" + mc + "   xid=" + xid + "," + onePhase);
        }

        Exception commitException = null;

        // Commit the transaction
        try {
            if (xares != null) {
                xares.commit(xid, onePhase);
                if (xid.equals(currentXid)) {
                    started = false;
                }
            } else {
                // Make sure that this call is for the XID
                if (currentXid == null || !currentXid.equals(xid) || !started) {
                    xalog.log(BasicLevel.ERROR, "passed xid(" + xid
                              + "),current Xid("
                              + currentXid
                              + "),started(" + started + ")");
                    throw new XAException("Commit: Must call correct XAResource for its started XID");
                }
                mc.connection.commit();
                started = false;
            }
        } catch (XAException xe) {
            xalog.log(BasicLevel.ERROR, xe.getMessage());
            commitException = xe;
            throw xe;
        } catch (SQLException e) {
            // Only store the exception at this point since the
            // connection cannot be removed until the auto-commit
            // mode has been reset
            commitException = e;
            XAExceptionUtils.throwXAException("Error on commit", e);
        } finally {

            // Reset the auto-commit flag
            try {
                mc.setAutoCommit(true);
            } catch (Exception exc) {
                if (xares == null) {
                    if (xalog.isLoggable(BasicLevel.DEBUG)) {
                        xalog.log(BasicLevel.DEBUG,
                                  "Unable to set autoCommit to true:", exc);
                    }
                }
            }
            if (commitException != null) {
                // this must be done after the setAutoCommit(true) to make remove Connection work.
                xalog.log(BasicLevel.ERROR, commitException.getMessage());
                // Notify the listeners of the error (will try to remove
                // the connection of the busy list)
                try {
                    mc.signalEvent(ConnectionEvent.CONNECTION_ERROR_OCCURRED, null, commitException);
                } catch (Exception ex) {
                    xalog.log(BasicLevel.WARN, ex.getMessage());
                }
            }
        }
    }

    /**
     * Ends the transaction
     * @param xid transaction xid
     * @param flags One of TMSUCCESS, TMFAIL, or TMSUSPEND. 
     */
    public void end(Xid xid, int flags) throws XAException {
        if (xalog.isLoggable(BasicLevel.DEBUG)) {
            xalog.log(BasicLevel.DEBUG, "mc=" + mc + "   xid=" + xid + "," + flags);
        }
        // Make sure that the Xid has started
        if (currentXid == null || !currentXid.equals(xid)) {
            throw new XAException(XAException.XA_RBPROTO);
        }
        if (!started && ended) {
            throw new XAException(XAException.XA_RBPROTO);
        }
        ended = true;
        if (xares != null) {
            xares.end(xid, flags);
        }
    }

    /**
     * Need to forget the heuristically completed Xid
     */
    public void forget(Xid xid) throws XAException {
        if (xalog.isLoggable(BasicLevel.DEBUG)) {
            xalog.log(BasicLevel.DEBUG, "mc=" + mc + "   xid=" + xid);
        }
        if (xares != null) {
            xares.forget(xid);
        }
    }

    /**
     * Get the current transaction timeout for this XAResource
     */
    public int getTransactionTimeout() throws XAException {
        if (xares != null) {
            return xares.getTransactionTimeout();
        }
        return 0;
    }

    /**
     * Determine if the resource manager instance is the same as the
     * resouce manager being passed in
     */
    public boolean isSameRM(XAResource xaRes) throws XAException {

        boolean ret = false;
        if (xaRes.equals(this)) {
            ret = true;
        } else if (!(xaRes instanceof XAResourceImpl)) {
            ret = false;
        } else {
            XAResourceImpl xaResImpl = (XAResourceImpl) xaRes;
            if (mc == xaResImpl.mc) {
                ret = true;
            }
        }
        if (xalog.isLoggable(BasicLevel.DEBUG)) {
            xalog.log(BasicLevel.DEBUG, "" + xaRes + "," + this + " is " + ret);
        }
        return ret;
    }

    /**
     * Prepare the Xid for a transaction commit
     */
    public int prepare(Xid xid) throws XAException {
        if (xalog.isLoggable(BasicLevel.DEBUG)) {
            xalog.log(BasicLevel.DEBUG, "mc=" + mc + "   xid=" + xid);
        }
        if (xares != null) {
            int ret = xares.prepare(xid);
            if (ret == XA_RDONLY) {
                // Cannot setAutocommit here, because still in global tx.
                started = false;
            }
            return ret;
        }
        // Just return true, since we are just simulating XA with our wrapper
        return XA_OK;
    }

    /**
     * Obtain a list of prepared transaction branches from a resource manager.
     */
    public Xid[] recover(int flag) throws XAException {
        if (xalog.isLoggable(BasicLevel.DEBUG)) {
            xalog.log(BasicLevel.DEBUG, "mc=" + mc);
        }
        if (xares != null) {
            return xares.recover(flag);
        }
        // Not a full RM, so just return null
        return null;
    }

    /**
     * Roll back work done on the Xid
     */
    public void rollback(Xid xid) throws XAException {
        if (xalog.isLoggable(BasicLevel.DEBUG)) {
            xalog.log(BasicLevel.DEBUG, "mc=" + mc + "   xid=" + xid);
        }

        Exception rbException = null;

        // Rollback the Xid
        try {
            if (xares != null) {
                xares.rollback(xid);
                if (xid.equals(currentXid)) {
                    started = false;
                }
            } else {
                // Make sure that this call is for the XID
                if (currentXid == null || !currentXid.equals(xid) || !started) {
                    xalog.log(BasicLevel.ERROR, "passed xid(" + xid
                              + "),current Xid(" + currentXid
                              + "),started(" + started + ")");
                    throw new XAException("Rollback: Must call correct XAResource for its started XID");
                }
                if (mc.connection != null) {
                    mc.connection.rollback();
                }
                started = false;
            }
        } catch (XAException xe) {
            xalog.log(BasicLevel.ERROR, xe.getMessage());
            rbException = xe;
            throw xe;
        } catch (SQLException e) {
            rbException = e;
            XAExceptionUtils.throwXAException("Error on rollback", e);
        } finally {
            // Reset the state of the Connection
            try {
                mc.setAutoCommit(true);
            } catch (Exception exc) {
                if (xares == null) {
                    if (xalog.isLoggable(BasicLevel.DEBUG)) {
                        xalog.log(BasicLevel.DEBUG,
                                  "Unable to set autoCommit to true:", exc);
                    }
                }
            }

            // If there was a SQL error
            // Try to remove the connection from the pool
            if (rbException != null) {
                try {
                    xalog.log(BasicLevel.ERROR, rbException.getMessage());
                    mc.signalEvent(ConnectionEvent.CONNECTION_ERROR_OCCURRED, null, rbException);
                } catch (Exception ex) {
                    xalog.log(BasicLevel.WARN, ex.getMessage());
                }
            }
        }
    }

    /**
     * Set the current transaction timeout value for this XAResource
     */
    public boolean setTransactionTimeout(int seconds) throws XAException {
        if (xares != null) {
            return xares.setTransactionTimeout(seconds);
        }
        return false;
    }

    /**
     * Start work on this Xid.  If TMJOIN is on, then join an existing transaction
     * already started by the RM.
     */
    public void start(Xid xid, int flags) throws XAException {
        if (xalog.isLoggable(BasicLevel.DEBUG)) {
            xalog.log(BasicLevel.DEBUG, "" + xid + "," + flags);
        }
        try {
            mc.setAutoCommit(false);
        } catch (Exception ex) {
            ex.printStackTrace();
            xalog.log(BasicLevel.ERROR,
                      "Unable to set autoCommit to false:" + ex.getMessage());
            XAExceptionUtils.throwXAException("Error : Unable to set autoCommit to false in start", ex);
        }

        if (xares != null) {
            xares.start(xid, flags);
        } else {
            if (started && (currentXid == null || !currentXid.equals(xid))) {
                xalog.log(BasicLevel.ERROR,
                          "Must call correct XAResource for its started XID");
                throw new XAException("XAResourceImpl.start : Must call correct XAResource for its started XID");
            }
        }
        currentXid = xid;
        started = true;
        ended = false;
    }
}
