/*
 * 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.easybeans;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.enterprise.inject.spi.InjectionTarget;

import org.jboss.weld.manager.api.WeldManager;
import org.ow2.easybeans.api.bean.EasyBeansBean;
import org.ow2.easybeans.container.EmptyResourceInjector;
import org.ow2.util.annotation.processor.DefaultAnnotationProcessor;
import org.ow2.util.annotation.processor.IAnnotationProcessor;
import org.ow2.util.annotation.processor.ProcessorException;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * <p>This class manage injection of CDI beans into EJBs.</p>
 * <p><b>Warning:</b> to be active this injector should be configured through the
 * {@link WeldResourceInjector#setBeanManager(org.jboss.weld.manager.api.WeldManager)}</p>
 *
 * @author Loic Albertin
 */
public class WeldResourceInjector extends EmptyResourceInjector {

    /**
     * Logger.
     */
    private static Log logger = LogFactory.getLog(WeldResourceInjector.class);

    /**
     * The bean manager
     */
    WeldManager beanManager = null;

    /**
     * A map where result of injection for EJBs should be stored in order to be later disposed.
     */
    Map<EasyBeansBean, Set<InjectionItemHolder>> injectionTargets;

    /**
     * An @Inject annotation processor
     */
    IAnnotationProcessor injectAnnotationProcessor;


    public WeldResourceInjector() {
        injectionTargets = new HashMap<EasyBeansBean, Set<InjectionItemHolder>>();
    }

    @Override
    public void preEasyBeansInject(EasyBeansBean bean) {
        if (injectAnnotationProcessor != null) {
            try {
                // Process bean to see if it contains @Inject annotations
                injectAnnotationProcessor.process(bean);
            } catch (ProcessorException e) {
                logger.error("Cannot inject CDI resources on bean {0}", bean, e);
            }
        }
    }

    @Override
    public void postEasyBeansDestroy(EasyBeansBean bean) {
        Set<InjectionItemHolder> injectionTargetSet = injectionTargets.remove(bean);
        if (injectionTargetSet != null) {
            // Dispose injected instance for this bean
            for (InjectionItemHolder injectionItemHolder : injectionTargetSet) {
                InjectionTarget injectionTarget = injectionItemHolder.getInjectionTarget();
                Object instance = injectionItemHolder.getInstance();
                injectionTarget.preDestroy(instance);
                injectionTarget.dispose(instance);
            }
        }
    }

    /**
     * This method should be call in order to set the {@link WeldManager} and create an appropriate {@link WeldInjectAnnotationHandler}.
     *
     * @param beanManager the bean manager
     */
    public void setBeanManager(WeldManager beanManager) {
        this.beanManager = beanManager;
        injectAnnotationProcessor = new DefaultAnnotationProcessor();
        injectAnnotationProcessor.addAnnotationHandler(new WeldInjectAnnotationHandler(this.beanManager, injectionTargets));
    }

}
