/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2012 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 (at your option) 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 *  $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.cdi.weld.internal.ejb;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

import org.ow2.easybeans.api.bean.EasyBeansSFSB;
import org.ow2.easybeans.container.session.SessionFactory;
import org.ow2.easybeans.container.session.stateful.StatefulSessionFactory;
import org.ow2.easybeans.proxy.client.AbsInvocationHandler;

/**
 * This class extends {@link EZBSessionObjectReference} in order to provides special behaviors for Stateful beans
 *
 * @author Loic Albertin
 */
public class SFSBObjectReference extends EZBSessionObjectReference<EasyBeansSFSB> {

    private static final long serialVersionUID = 7918660774920429745L;

    /**
     * The Stateful bean id
     */
    private Long beanId = null;

    /**
     * The last used {@link AbsInvocationHandler}
     */
    private AbsInvocationHandler ezbInvocationHandler = null;

    public SFSBObjectReference(SessionFactory<EasyBeansSFSB> factory) {
        super(factory);
        beanId = ((StatefulSessionFactory) factory).generateNewId();
        this.getSessionContext().setBeanId(beanId);
    }

    @Override
    public <S> S getBusinessObject(Class<S> businessInterfaceType) {
        S businessObject = super.getBusinessObject(businessInterfaceType);
        if (Proxy.isProxyClass(businessObject.getClass())) {
            InvocationHandler invocationHandler = Proxy.getInvocationHandler(businessObject);
            if (invocationHandler instanceof AbsInvocationHandler) {
                ezbInvocationHandler = (AbsInvocationHandler) invocationHandler;
            }
        }
        return businessObject;
    }

    @Override
    public boolean isRemoved() {
        if (ezbInvocationHandler == null) {
            return false;
        }
        return ezbInvocationHandler.isRemoved();
    }

    @Override
    public void remove() {
        ezbInvocationHandler.setRemoved(true);
    }
}
