/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
package com.sun.enterprise.resource;

import javax.transaction.xa.*;
import javax.resource.spi.*;
import com.sun.enterprise.log.Log;
import com.sun.enterprise.*;
import com.sun.enterprise.distributedtx.*;
import java.util.logging.*;
import java.util.Hashtable;
import java.util.HashMap;
import java.util.ArrayList;
import com.sun.logging.*;
import javax.resource.ResourceException;
import com.sun.jts.CosTransactions.Configuration;

/**
 * @author Tony Ng
 *
 */
public class ConnectorXAResource implements XAResource {

    private Object userHandle;
    private ResourceSpec spec;
    private String poolName;
    private ResourceAllocator alloc;
    private PoolManager poolMgr;
    private ManagedConnection localConnection;
    private ClientSecurityInfo info;
    private ConnectionEventListener listener;
    private ResourceHandle localHandle_;

    private static Hashtable listenerTable = new Hashtable();

    private static ThreadLocal sharedConnections = new ThreadLocal();


    // Create logger object per Java SDK 1.4 to log messages
    // introduced Santanu De, Sun Microsystems, March 2002

    static Logger _logger = LogDomains.getLogger(LogDomains.RSR_LOGGER);



    public ConnectorXAResource(ResourceHandle handle,
                               ResourceSpec spec,
                               ResourceAllocator alloc,
                               ClientSecurityInfo info ) {

        // initially userHandle is associated with mc
        this.poolMgr = Switch.getSwitch().getPoolManager();
        this.userHandle = null;
        this.spec = spec;
	this.poolName = spec.getConnectionPoolName();
        this.alloc = alloc;
        this.info = info;
        localConnection = (ManagedConnection) handle.getResource();
	localHandle_ = handle;
    }

    public void setUserHandle(Object userHandle) {
        this.userHandle = userHandle;
    }

    private void handleResourceException(Exception ex)
        throws XAException {
        _logger.log(Level.SEVERE,"poolmgr.system_exception",ex);
        XAException xae = new XAException(ex.toString());
        xae.errorCode = XAException.XAER_RMERR;
        throw xae;
    }

    public void commit(Xid xid, boolean onePhase) throws XAException {
        try {
	    ResourceHandle handle = getResourceHandle();
	    ManagedConnection mc = (ManagedConnection) handle.getResource();
            mc.getLocalTransaction().commit();
        } catch (Exception ex) {
            handleResourceException(ex);
        }
    }

    public void start(Xid xid, int flags) throws XAException {
        try {
	    ResourceHandle handle = getResourceHandle();
	    if ( ! localHandle_.equals( handle) ) {
	        ManagedConnection mc = (ManagedConnection) handle.getResource();
                mc.associateConnection(userHandle);
                LocalTxConnectionEventListener l = 
                     (LocalTxConnectionEventListener) handle.getListener();
                l.associateHandle(userHandle, localHandle_);
	    }	
        } catch (Exception ex) {
            handleResourceException(ex);
        }
    }

    public void end(Xid xid, int flags) throws XAException {
        try {
	    ResourceHandle handle = getResourceHandle();
	    if (! localHandle_.equals( handle ) ) {
	        ManagedConnection mc = (ManagedConnection) handle.getResource();
                localConnection.associateConnection(userHandle);
                LocalTxConnectionEventListener l = 
                     (LocalTxConnectionEventListener) handle.getListener();
                l.removeAssociation(userHandle);
	    }	
        } catch (Exception ex) {
            handleResourceException(ex);
        }
    }
    
    public void forget(Xid xid) throws XAException {
	_logger.fine("Well, forget is called for xid :"+xid);
        // no-op
    }

    public int getTransactionTimeout() throws XAException {
        return 0;
    }
    
    public boolean isSameRM(XAResource other) throws XAException {
        if (this == other) return true;
        if (other == null) return false;
        if (other instanceof ConnectorXAResource) {
            ConnectorXAResource obj = (ConnectorXAResource) other;
            return (this.spec.equals(obj.spec) &&
                    this.info.equals(obj.info));
        } else {
            return false;
        }
    }        

    public int prepare(Xid xid) throws XAException {
	return Configuration.LAO_PREPARE_OK;
    }
    
    public Xid[] recover(int flag) throws XAException {
        return new Xid[0];
    }
    
    public void rollback(Xid xid) throws XAException {
        try {
	    ResourceHandle handle = getResourceHandle();
	    ManagedConnection mc = (ManagedConnection) handle.getResource();
            mc.getLocalTransaction().rollback();
        } catch (Exception ex) {
            handleResourceException(ex);
        }
    }

    public boolean setTransactionTimeout(int seconds) throws XAException {
        return false;
    }

    public static void freeListener(ManagedConnection mc) {
        listenerTable.remove(mc);
    }

    public static void addListener(ManagedConnection mc, ConnectionEventListener l) {
        listenerTable.put(mc,l);
    }

    private ResourceHandle getResourceHandle() throws PoolingException {
        try {
            ResourceHandle h = null;
            J2EETransactionManager txMgr = Switch.getSwitch().getTransactionManager();
            J2EETransaction j2eetran = (J2EETransaction) txMgr.getTransaction();
            if (j2eetran == null) {      //Only if some thing is wrong with tx manager.
                h = localHandle_;        //Just return the local handle.
            } else {
                h = j2eetran.getNonXAResource();
            }
	    if (h.getResourceState().isUnenlisted()) {
	        ManagedConnection mc = (ManagedConnection) h.getResource();
                // begin the local transaction if first time
                // this ManagedConnection is used in this JTA transaction
                mc.getLocalTransaction().begin();
            }
            return h;
        } catch (Exception ex) {
            _logger.log(Level.SEVERE,"poolmgr.system_exception",ex);
            throw new PoolingException(ex.toString(), ex);
	}
    }

}
