/*
 * Copyright (C) 2012  Bull S. A. S.
 * Bull, Rue Jean Jaures, B.P.68, 78340, Les Clayes-sous-Bois
 * 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
 * version 2.1 of the License.
 * 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
 * program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
 * Floor, Boston, MA  02110-1301, USA.
 */

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

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Provides;
import org.ow2.easybeans.api.Factory;
import org.ow2.easybeans.api.binding.EZBRef;

/**
 * An OSGi-iPOJO component providing {@link EZBFactoriesRegistry} service
 *
 * @author Loic Albertin
 */
@Component(immediate = true)
@Instantiate
@Provides
public class EZBFactoriesRegistryImpl implements EZBFactoriesRegistry {
    /**
     * The actual registry
     */
    private final Map<String, Map<String, Factory<?, ?>>> registry = new HashMap<String, Map<String, Factory<?, ?>>>();

    public void registerBeanFactory(Factory<?, ?> factory) {
        String moduleId = factory.getContainer().getConfiguration().getModuleName();
        String beanName = factory.getBeanInfo().getName();
        synchronized (registry) {
            if (!registry.containsKey(moduleId)) {
                registry.put(moduleId, new HashMap<String, Factory<?, ?>>());
            }
            registry.get(moduleId).put(beanName, factory);
        }
    }

    public Factory<?, ?> getBeanFactory(String moduleName, String beanName) {
        synchronized (registry) {
            if (registry.containsKey(moduleName)) {
                return registry.get(moduleName).get(beanName);
            } else {
                return null;
            }
        }
    }


    public Collection<Factory<?, ?>> getFactories(String moduleName) {
        synchronized (registry) {
            if (registry.containsKey(moduleName)) {
                return Collections.unmodifiableCollection(registry.get(moduleName).values());
            } else {
                return Collections.emptyList();
            }
        }
    }

    public void unregisterFactories(String moduleName) {
        synchronized (registry) {
            registry.remove(moduleName);
        }
    }


}
