/**
 * 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$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.jndi.interceptors.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import javax.naming.Context;
import javax.naming.NamingException;

import org.objectweb.carol.jndi.intercept.ContextInterceptor;
import org.objectweb.carol.jndi.intercept.InterceptorManager;
import org.objectweb.carol.jndi.intercept.manager.SingletonInterceptorManager;
import org.objectweb.jonas.common.JProp;
import org.objectweb.jonas.common.Log;
import org.objectweb.jonas.jndi.checker.IResourceCheckerManager;
import org.objectweb.jonas.jndi.checker.impl.ResourceCheckerManager;
import org.objectweb.jonas.service.AbsServiceImpl;
import org.objectweb.jonas.service.ServiceException;
import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * Component that will create and register JNDI interceptors.
 * @author Florent Benoit
 */
public class JNDIInterceptorsComponent extends AbsServiceImpl {
	
	private static final String PROPERTY_BASE = "jonas.service.jndi-intercept";
	
	private static final String INTERCEPTORS = PROPERTY_BASE + ".context-interceptors";

    /**
     * Logger.
     */
    private Logger logger = Log.getLogger(JNDIInterceptorsComponent.class.getName());

    /**
     * List of context interceptors.
     */
    private List interceptors = new ArrayList();
    
    /**
     * Link to the resource checker manager.
     */
    private IResourceCheckerManager resourceCheckerManager = null;

    /**
     * Link to the interceptor manager.
     */
    private InterceptorManager interceptorManager = null;

	protected void doInit(final Context ctx) throws ServiceException {
		
		this.resourceCheckerManager = new ResourceCheckerManager();
		this.interceptorManager = SingletonInterceptorManager.getInterceptorManager();
		
		// Get the list of the interceptors names
        String contextInterceptorsStr = null;
        try {
            contextInterceptorsStr = (String) ctx.lookup(INTERCEPTORS);
        } catch (NamingException e) {
            // No problem if there is no value for 'context-interceptors'
        }
        if (contextInterceptorsStr != null) {
            StringTokenizer st = new StringTokenizer(contextInterceptorsStr, ",");
            while (st.hasMoreTokens()) {
                String className = st.nextToken().trim();
        		try {
					// Load the interceptor class
					Class clazz = Class.forName(className);
					ContextInterceptor interceptor = (ContextInterceptor) clazz.newInstance();
					
					// Try to inject the ResourceCheckerManager
					if (AbsContextInterceptor.class.isAssignableFrom(clazz)) {
						AbsContextInterceptor abs = (AbsContextInterceptor) interceptor;
						abs.setResourceCheckerManager(resourceCheckerManager);
					}
					
					interceptors.add(interceptor);
                    logger.log(BasicLevel.DEBUG, "Interceptor '" + className + "' loaded.");
				} catch (Exception e) {
					logger.log(BasicLevel.WARN, "Interceptor '" + className + "' cannot be loaded. It will be ignored", e);
				}
            }
        }


	}

	protected void doStart() throws ServiceException {

        // Register all interceptors
        for (Iterator i = interceptors.iterator(); i.hasNext();) {
        	ContextInterceptor contextInterceptor = (ContextInterceptor) i.next();
        	
            if (logger.isLoggable(BasicLevel.DEBUG)) {
				logger.log(BasicLevel.DEBUG,
						"Registering the context interceptor '"
								+ contextInterceptor + "'");
			}
			interceptorManager.registerContextInterceptor(contextInterceptor);
        }

	}

	protected void doStop() throws ServiceException {

        // Unregister all interceptors
        for (Iterator i = interceptors.iterator(); i.hasNext();) {
        	ContextInterceptor contextInterceptor = (ContextInterceptor) i.next();
        	interceptorManager.unregisterContextInterceptor(contextInterceptor);
        }

	}
}
