/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */

package org.jfox.ejb;

import java.lang.reflect.Proxy;
import java.security.Identity;
import java.security.Principal;
import java.util.Properties;
import javax.ejb.EJBContext;
import javax.ejb.EJBException;
import javax.ejb.EJBHome;
import javax.ejb.EJBLocalHome;
import javax.ejb.TimerService;

import org.jfox.ejb.connector.ContainerRemote;
import org.jfox.ejb.connector.local.LOCALContainerInvoker;
import org.jfox.ejb.connector.local.LOCALContainerService;
import org.jfox.framework.Registry;
import org.jfox.framework.logger.Logger;

/**
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public abstract class EJBContextSupport implements EJBContext {
    protected Logger logger = Logger.getLogger(getClass().getName());
    protected EJBObjectId objectId = null;
    protected BucketMetaData bucketMeta = null;

    public EJBContextSupport(EJBObjectId objectId, BucketMetaData bucketMeta) {
        this.objectId = objectId;
        this.bucketMeta = bucketMeta;
    }

    // use LOCALContainerInvoker & LOCALContainerService
    public EJBHome getEJBHome() {
        ClassLoader ctxLoader = Thread.currentThread().getContextClassLoader();
        // get the EJBObject class name
        String ejbHomeInterfaceName = objectId.getHomeInterfName();
        try {
            Class remoteInterface = ctxLoader.loadClass(ejbHomeInterfaceName);
            return (EJBHome) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                    new Class[]{remoteInterface},
//              new LOCALContainerInvoker(objectId,LOCALContainerService.getInstance()));
                    new LOCALContainerInvoker(objectId, (ContainerRemote) (Registry.getInstance().getFirstComponentMetabyImplemetation(LOCALContainerService.class)).getComponentInstance()));
        }
        catch(Exception e) {
            throw new EJBException(e);
        }

    }

    public EJBLocalHome getEJBLocalHome() {
        throw new IllegalStateException("current not support local ejb");
    }

    public Properties getEnvironment() {
        throw new EJBException("Deprecated");
    }

    public Identity getCallerIdentity() {
        throw new EJBException("Deprecated");
    }

    public Principal getCallerPrincipal() {
        throw new IllegalStateException("current not support security context");
    }

    public boolean isCallerInRole(Identity identity) {
        throw new EJBException("Deprecated");
    }

    public boolean isCallerInRole(String string) {
        throw new IllegalStateException("current not support security context");
    }

    //TODO: implement Timer Service
    public TimerService getTimerService() throws IllegalStateException {
        return ContainerImpl.getInstance().getBucket(bucketMeta.getEJBDescriptor().getEjbName()).getTimerService();
    }

}
