/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 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.resource;

import javax.resource.ResourceException;
import javax.resource.spi.LocalTransaction;

import javax.transaction.xa.XAResource;
import javax.transaction.xa.XAException;
import javax.transaction.xa.Xid;

import org.objectweb.util.monolog.api.Logger;
import org.objectweb.util.monolog.api.BasicLevel;

/**
 *  A LocalXAWrapper that intercepts the XA calls for an RAR that only
 *   supports LocalTransactions and translates them to the appropriate
 *   Local Transaction methods.
 *
 * @author     Eric.Hardesty@bull.com
 */
public final class LocalXAWrapper implements XAResource {

    /**
     *  The Logger instance where messages are written.
     */
    private static Logger logger = null;

    /**
     *  State of the transaction (See XA protocol)
     */
    protected static final int XA_NONE = 0;
    protected static final int XA_STARTED = 1;
    protected static final int XA_SUSPENDED = 2;
    protected static final int XA_ENDED = 3;
    protected static final int XA_FAILED = 4;
    protected int txstate = XA_NONE;

    /*
     * Xid of the current transaction.
     */
    private Xid currentXid = null;

    /**
     *  The LocalTransaction object to make the begin(), commit(),
     *    and rollback() calls.
     */
    protected LocalTransaction localTrans = null;

    /**
     * constructor
     */
    LocalXAWrapper(LocalTransaction _localTrans, Logger _logger) {
        localTrans = _localTrans;
        logger = _logger;
    }

    /**
     * Only start a local transaction if a new transaction is being
     * attempted
     *
     * @param xid transaction xid
     * @exception  XAException  Transaction already started or error
     *                          starting a new local transaction
     */
    public void start(Xid xid, int flags) throws XAException {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "Xid =" + xid + "flags=" + flags);
        }
        // Check XA state
        switch (txstate) {
        case XA_NONE:
        case XA_ENDED:
            if (flags == XAResource.TMRESUME) {
                throw new XAException("RESUME without SUSPEND");
            }
            if (flags == XAResource.TMJOIN) {
                // Nothing to do in that case ?
                break;
            }
            try {
                localTrans.begin();
                currentXid = xid;
                txstate = XA_STARTED;
            } catch (ResourceException res) {
                XAException xaE = new XAException("LocalTransaction.begin failed");
                xaE.initCause(res);
                throw xaE;
            }
            break;
        case XA_STARTED:
            throw new XAException("XA_START called twice");
        case XA_SUSPENDED:
            if (flags != XAResource.TMRESUME) {
                logger.log(BasicLevel.WARN, "XA_START should have the TMRESUME flag set");
                // Not sure what to do in that case
            }
            txstate = XA_STARTED;
            break;
        case XA_FAILED:
            logger.log(BasicLevel.WARN, "XA_END has been called with TMFAIL");
            break;
        }
    }

    /**
     * Ends the transaction
     * No method to map for a local transaction.
     * @param xid transaction xid
     * @param flags One of TMSUCCESS, TMFAIL, or TMSUSPEND. 
     */
    public void end(Xid xid, int flags) throws XAException {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "Xid =" + xid + "flags=" + flags);
        }
        // Make sure that the Xid has started
        if (currentXid == null || !currentXid.equals(xid)) {
            throw new XAException(XAException.XA_RBPROTO);
        }
        switch (txstate) {
        case XA_NONE:
            logger.log(BasicLevel.WARN, "XA START has not been called");
            throw new XAException("Commit: XA START has not been called");
        case XA_STARTED:
            break;
        case XA_ENDED:
            logger.log(BasicLevel.WARN, "XA END has already been called");
            break;
        case XA_SUSPENDED:
            logger.log(BasicLevel.WARN, "XA END has already been called");
            break;
        case XA_FAILED:
            logger.log(BasicLevel.WARN, "XA_END has been called with TMFAIL");
            throw new XAException(XAException.XA_RBPROTO);
        }
    }

    /**
     * No method to map for a local transaction.
     * @param xid transaction xid
     */
    public void forget(Xid xid) throws XAException {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "" + xid);
        }
    }

    /**
     *  No method to map for a local transaction, just
     *   return no timeout.
     */
    public int getTransactionTimeout() throws XAException {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }
        return -1;
    }

    /**
     * Determine if the wrapper instance is the same as the
     * wrapper instance being passed in
     * @param xaresource An XAResource object
     * @return True if same RM instance, otherwise false.
     * @throws XAException no throw in this implementation
     */
    public boolean isSameRM(XAResource xaresource) throws XAException {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }

        if (xaresource.equals(this)) {
            if (logger.isLoggable(BasicLevel.DEBUG)) {
                logger.log(BasicLevel.DEBUG, "isSameRM = true " + this);
            }
            return true;
        }
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "isSameRM = false " + this);
        }
        return false;
    }

    /**
     *  No method to map for a local transaction, just return XA_OK.
     *@param xid transaction xid
     */
    public int prepare(Xid xid) throws XAException {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }
        return XAResource.XA_OK;
    }

    /**
     *  No method to map for a local transaction.
     */
    public Xid[] recover(int i) throws XAException {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }
        return null;
    }

    /**
     * Commit the localTransaction
     *
     * @param xid transaction xid
     * @param onePhase for interface compliance (ignored because forced)
     * @exception  XAException  Exception trying to commit local transaction
     */
    public void commit(Xid xid, boolean onePhase) throws XAException {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "Xid =" + xid + "onePhase=" + onePhase);
        }

        // check XA protocol
        if (currentXid == null || !currentXid.equals(xid)) {
            logger.log(BasicLevel.WARN, "Must call correct XAResource for its started XID");
            throw new XAException("Commit: Must call correct XAResource for its started XID");
        }
        switch (txstate) {
        case XA_NONE:
            logger.log(BasicLevel.WARN, "XA START has not been called");
            throw new XAException("Commit: XA START has not been called");
        case XA_STARTED:
            // We decide that XA_END missing is not really an error.
            logger.log(BasicLevel.DEBUG, "XA_END has not been called");
        case XA_ENDED:
            break;
        case XA_SUSPENDED:
            logger.log(BasicLevel.WARN, "transaction suspended");
            // ignore this.
            break;
        case XA_FAILED:
            logger.log(BasicLevel.WARN, "XA_END has been called with TMFAIL");
            // Should rollback here ?
            break;
        }

        // commit the local transaction.
        try {
            localTrans.commit();
        } catch (ResourceException res) {
            XAException xaE = new XAException(res.getMessage());
            xaE.initCause(res);
            throw xaE;
        } finally {
            txstate = XA_NONE;
            currentXid = null;
        }
    }

    /**
     * Rollback the localTransaction
     * @param xid transaction xid
     * @exception  XAException  Exception trying to rollback local transaction
     */
    public void rollback(Xid xid) throws XAException {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "Xid =" + xid);
        }

        // check XA protocol
        if (currentXid == null || !currentXid.equals(xid)) {
            logger.log(BasicLevel.WARN, "Must call correct XAResource for its started XID");
            throw new XAException("Commit: Must call correct XAResource for its started XID");
        }
        switch (txstate) {
        case XA_NONE:
            logger.log(BasicLevel.WARN, "XA START has not been called");
            throw new XAException("Commit: XA START has not been called");
        case XA_STARTED:
            // We decide that XA_END missing is not really an error.
            logger.log(BasicLevel.DEBUG, "XA_END has not been called");
        case XA_ENDED:
            break;
        case XA_SUSPENDED:
            logger.log(BasicLevel.WARN, "transaction suspended");
            // ignore this.
            break;
        case XA_FAILED:
            break;
        }

        try {
            localTrans.rollback();
        } catch (ResourceException res) {
            XAException xaE = new XAException("Rollback failed");
            xaE.initCause(res);
            throw xaE;
        } finally {
            txstate = XA_NONE;
            currentXid = null;
        }
    }

    /**
     *  No method to map for a local transaction, just
     *   return no timeout.
     */
    public boolean setTransactionTimeout(int i) throws XAException {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }
        return false;
    }

}
