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

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.core.JdkVersion;
import org.springframework.util.StringUtils;

/**
 * TODO: JAVADOC
 * Parser for the &lt;context:mbean-export/&gt; element.
 *
 * <p>Registers an instance of
 * {@link org.springframework.jmx.export.annotation.AnnotationMBeanExporter}
 * within the context.
 *
 * @author Juergen Hoeller
 * @author Mark Fisher
 * @since 2.5
 * @see org.springframework.jmx.export.annotation.AnnotationMBeanExporter
 */
class MBeanExportBeanDefinitionParser {

    private static final String MBEAN_EXPORTER_BEAN_NAME = "mbeanExporter";

    protected AbstractBeanDefinition parse(MBeanExportDeclaration declaration, BeanDefinitionRegistry registry) {
        String beanClassName = (JdkVersion.isAtLeastJava15() ?
                "org.springframework.jmx.export.annotation.AnnotationMBeanExporter" :
                "org.springframework.jmx.export.MBeanExporter");
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(beanClassName);
        builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);

        String defaultDomain = declaration.getDefaultDomain();
        if(StringUtils.hasText(defaultDomain))
            builder.addPropertyValue("defaultDomain", defaultDomain);

        String serverBeanName = declaration.getServerBeanName();
        if (StringUtils.hasText(serverBeanName)) {
            builder.addPropertyReference("server", serverBeanName);
        }
        else {
            AbstractBeanDefinition specialServer = MBeanServerBeanDefinitionParser.findServerForSpecialEnvironment();
            if (specialServer != null) {
                builder.addPropertyValue("server", specialServer);
            }
        }

        RegistrationPolicy policy = declaration.getRegistrationPolicy();
        builder.addPropertyValue("registrationBehavior", policy.getPolicyCode());

        registry.registerBeanDefinition(MBEAN_EXPORTER_BEAN_NAME, builder.getBeanDefinition());

        return null;
    }

}
