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

import org.springframework.beans.BeanMetadataAttribute;
import org.springframework.beans.BeanMetadataAttributeAccessor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import org.springframework.config.java.annotation.Configuration;
import org.springframework.config.java.internal.model.ConfigurationClass;

import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;

import java.io.IOException;


/**
 * TODO: ELIMINATE - see SJC-228
 * Detects the presence of any {@link Configuration @Configuration} bean definitions and annotates
 * them with {@link BeanMetadataAttribute bean metadata}. For use only when bootstrapping JavaConfig
 * via XML.
 *
 * @author  Chris Beams
 */
class ConfigurationBeanDefinitionDecoratingBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        for (String beanName : beanFactory.getBeanDefinitionNames()) {
            BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
            if (isConfigClass(beanDef))
                addConfigClassMetadata((BeanMetadataAttributeAccessor) beanDef);
        }
    }

    private void addConfigClassMetadata(BeanMetadataAttributeAccessor beanDef) {
        beanDef.addMetadataAttribute(new BeanMetadataAttribute(ConfigurationClass.IS_CONFIGURATION_CLASS, true));
    }

    private boolean isConfigClass(BeanDefinition beanDef) {
        BeanDefinition beanDefinition = beanDef;
        String className = beanDefinition.getBeanClassName();
        MetadataReader reader;

        try {
            reader = new SimpleMetadataReaderFactory().getMetadataReader(className);
        } catch (IOException e) {
            throw new BeanCreationException("problem reading class " + className, e);
        }

        return reader.getAnnotationMetadata().hasAnnotation(Configuration.class.getName());
    }

}
