/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2009 France Telecom R&D
 * 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: ResourceCheckerInterceptor.java 19876 2010-05-27 07:51:40Z benoitf $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.jndi.interceptors.impl.easybeans;

import java.util.List;
import java.util.ArrayList;

import javax.interceptor.InvocationContext;

import org.ow2.easybeans.api.EasyBeansInterceptor;
import org.ow2.easybeans.api.EasyBeansInvocationContext;
import org.ow2.easybeans.api.bean.EasyBeansSFSB;
import org.ow2.easybeans.api.Factory;
import org.ow2.jonas.jndi.checker.api.IResourceChecker;
import org.ow2.jonas.jndi.checker.api.IResourceCheckerManager;
import org.ow2.jonas.jndi.checker.api.ResourceCheckpoints;
import org.ow2.jonas.jndi.checker.api.IResourceCheckerInfo;

/**
 * Interceptors that will check if all resources have been closed.
 * @author Florent Benoit
 */
public class ResourceCheckerInterceptor implements EasyBeansInterceptor {


    /**
     * Keep a list of resources for stateful beans.
     */
    private List<IResourceChecker> resources = null;


    /**
     * Keep a list of resources for stateful beans.
     */
    private IResourceCheckerManager resourceCheckerManager = null;

    /**
     * Default constructor.
     */
    public ResourceCheckerInterceptor() {
        this.resources = new ArrayList<IResourceChecker>();
    }

     /**
     * Defines the interceptor schema of EasyBeans interceptors.
     * @param invocationContext context with useful attributes on the current
     *        invocation
     * @return result of the next invocation (to chain interceptors)
     * @throws Exception if interceptor fails
     */
    public Object intercept(EasyBeansInvocationContext invocationContext) throws Exception {
         // Get target
         Object target = invocationContext.getTarget();
         Factory factory = invocationContext.getFactory();

         // Needs to get the resource checker manager
         if (resourceCheckerManager == null) {
             resourceCheckerManager = factory.getContainer().getExtension(IResourceCheckerManager.class);
         }

         // Push a new list
         if (resourceCheckerManager != null) {
             resourceCheckerManager.push();
         }

         // Stateful ?
         EasyBeansSFSB statefulBean = null;
         if (target instanceof EasyBeansSFSB) {
             statefulBean = (EasyBeansSFSB) target;
         }

         // restore resources for stateful
         if (resourceCheckerManager != null) {
             if (statefulBean != null) {
                 for (IResourceChecker resource : resources) {
                     resourceCheckerManager.getResources().add(resource);
                 }
             }
         }

         // Call the next operation
         try {
             return invocationContext.proceed();
         } finally {
             // Stateful ? keep resources
             if (statefulBean != null) {
                 if (resourceCheckerManager != null) {
                     List<IResourceChecker> managerResources = resourceCheckerManager.getResources();
                     for (IResourceChecker managerResource : managerResources) {
                        if (!this.resources.contains(managerResource)) {
                            this.resources.add(managerResource);
                         }
                     }
                 }

                 // instance removed ?  perform the check
                 if (statefulBean.getEasyBeansRemoved()) {
                     for (IResourceChecker resource : resources) {
                        resource.detect(new EJBResourceCheckerInfo(factory, ResourceCheckpoints.EJB_PRE_DESTROY));
                    }
                 }

             } else {
                 if (resourceCheckerManager != null) {
                     resourceCheckerManager.detect(new EJBResourceCheckerInfo(factory, ResourceCheckpoints.EJB_POST_INVOKE));
                 }
             }
             // pop resources
             if (resourceCheckerManager != null) {
                 resourceCheckerManager.pop();
             }
         }
     }

}


/**
 * Checker info for EJB.
 * @author Florent Benoit
 */
class EJBResourceCheckerInfo implements IResourceCheckerInfo {

    /**
     * Caller info.
     */
    private String callerInfo = null;

    /**
     * Check point.
     */
    private ResourceCheckpoints checkPoint = null;

    /**
     * Build a checker info object based on the given request.
     * @param factory the given invocation context factory
     * @param checkPoint the given resource check point
     */
    public EJBResourceCheckerInfo(final Factory factory, final ResourceCheckpoints checkPoint) {
        this.callerInfo = factory.getContainer().getArchive() + ", Bean = " + factory.getBeanInfo().getName();
        this.checkPoint = checkPoint;
    }

    /**
     * Build a checker info object based on the given request.
     * @param checkPoint the given resource check point
     */
    public EJBResourceCheckerInfo(final ResourceCheckpoints checkPoint) {
        this.callerInfo = "None";
        this.checkPoint = checkPoint;
    }

    /**
     * @return checkpoint of the caller.
     */
    public ResourceCheckpoints getCheckPoint() {
            return checkPoint;
        }

    /**
     * @return data for identifying the current caller (EJB Name, Servlet Name, etc)
     */
    public String getCallerInfo() {
           return callerInfo;
    }

}
