/*
 * Copyright 2002-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.config.java.context;

import static org.springframework.util.ClassUtils.getDefaultClassLoader;

import org.springframework.beans.BeanMetadataAttribute;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;

import org.springframework.config.java.internal.factory.BeanFactoryProvider;
import org.springframework.config.java.internal.util.Constants;


/** TODO: JAVADOC */
public class DefaultBeanFactoryProvider implements BeanFactoryProvider {

    public void registerBeanDefinition(BeanDefinitionRegistry registry) {
        // register factory bean
        RootBeanDefinition factoryBean = new RootBeanDefinition();
        String factoryBeanName = this.getClass().getName();
        factoryBean.setBeanClassName(this.getClass().getName());
        factoryBean.addMetadataAttribute(new BeanMetadataAttribute(Constants.JAVA_CONFIG_IGNORE, true));

        registry.registerBeanDefinition(factoryBeanName, factoryBean);


        RootBeanDefinition bff = new RootBeanDefinition();
        bff.setFactoryBeanName(factoryBeanName);
        bff.setFactoryMethodName("createBeanFactory");
        bff.setScope(BeanDefinition.SCOPE_PROTOTYPE);
        bff.addMetadataAttribute(new BeanMetadataAttribute(Constants.JAVA_CONFIG_IGNORE, true));

        registry.registerBeanDefinition(BeanFactoryProvider.BEAN_NAME, bff);
    }

    public BeanFactory createBeanFactory(String className) throws Exception {
        return new JavaConfigApplicationContext(getDefaultClassLoader().loadClass(className));
    }

}
