/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.apache.struts2.config;

import org.apache.struts2.ObjectFactory;
import org.apache.struts2.config.BeanSelectionProvider;
import org.apache.struts2.config.Configuration;
import org.apache.struts2.config.ConfigurationException;
import org.apache.struts2.inject.*;
import org.apache.struts2.util.ClassLoaderUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.inject.Container;
import org.apache.struts2.inject.ContainerBuilder;
import org.apache.struts2.inject.Context;
import org.apache.struts2.inject.Factory;
import org.apache.struts2.inject.Scope;

import java.util.Properties;

/**
 * Base implementation of {@link BeanSelectionProvider} that provides bean aliasing functionality.
 * <p>
 * This class provides the {@link #alias(Class, String, ContainerBuilder, Properties, Scope)} method
 * which is used to select and register bean implementations based on configuration properties.
 * </p>
 *
 * <h2>Bean Selection Process</h2>
 * <p>
 * The {@code alias} method selects a bean implementation using the following process:
 * </p>
 * <ol>
 *   <li>Read the property value for the given key from the configuration properties</li>
 *   <li>If no property is set, use {@value #DEFAULT_BEAN_NAME} as the default bean name</li>
 *   <li>Check if a bean with that name already exists in the container:
 *       <ul>
 *         <li>If found, alias it to {@link Container#DEFAULT_NAME} making it the default</li>
 *         <li>If not found, try to load the property value as a fully qualified class name</li>
 *       </ul>
 *   </li>
 *   <li>If class loading succeeds, register the class as a factory for the interface type</li>
 *   <li>If class loading fails and the name is not the default, create a delegate factory
 *       that will resolve the bean through {@link ObjectFactory} at runtime. This allows
 *       Spring bean names to be used in configuration.</li>
 * </ol>
 *
 * <h2>Usage Example</h2>
 * <pre>
 * // In struts.properties or struts.xml:
 * // struts.objectFactory = spring
 * // struts.converter.collection = myCustomCollectionConverter
 *
 * // In a subclass:
 * alias(ObjectFactory.class, StrutsConstants.STRUTS_OBJECTFACTORY, builder, props);
 * alias(CollectionConverter.class, StrutsConstants.STRUTS_CONVERTER_COLLECTION, builder, props);
 * </pre>
 *
 * @see BeanSelectionProvider
 * @see StrutsBeanSelectionProvider
 */
public abstract class AbstractBeanSelectionProvider implements BeanSelectionProvider {

    private static final Logger LOG = LogManager.getLogger(AbstractBeanSelectionProvider.class);

    public static final String DEFAULT_BEAN_NAME = "struts";

    public void destroy() {
        // NO-OP
    }

    public void loadPackages() throws ConfigurationException {
        // NO-OP
    }

    public void init(Configuration configuration) throws ConfigurationException {
        // NO-OP
    }

    public boolean needsReload() {
        return false;
    }

    protected void alias(Class type, String key, ContainerBuilder builder, Properties props) {
        alias(type, key, builder, props, Scope.SINGLETON);
    }

    protected void alias(Class type, String key, ContainerBuilder builder, Properties props, Scope scope) {
        if (!builder.contains(type, Container.DEFAULT_NAME)) {
            String foundName = props.getProperty(key, DEFAULT_BEAN_NAME);
            if (builder.contains(type, foundName)) {
                LOG.trace("Choosing bean ({}) for ({})", foundName, type.getName());
                builder.alias(type, foundName, Container.DEFAULT_NAME);
            } else {
                try {
                    Class cls = ClassLoaderUtil.loadClass(foundName, this.getClass());
                    LOG.trace("Choosing bean ({}) for ({})", cls.getName(), type.getName());
                    builder.factory(type, cls, scope);
                } catch (ClassNotFoundException ex) {
                    // Perhaps a spring bean id, so we'll delegate to the object factory at runtime
                    LOG.trace("Choosing bean ({}) for ({}) to be loaded from the ObjectFactory", foundName, type.getName());
                    if (DEFAULT_BEAN_NAME.equals(foundName)) {
                        LOG.trace("No bean registered for type ({}) with default name '{}', skipping as optional", type.getName(), DEFAULT_BEAN_NAME);
                    } else {
                        if (ObjectFactory.class != type) {
                            builder.factory(type, new ObjectFactoryDelegateFactory(foundName, type), scope);
                        } else {
                            throw new ConfigurationException("Cannot locate the chosen ObjectFactory implementation: " + foundName);
                        }
                    }
                }
            }
        } else {
            LOG.warn("Unable to alias bean type ({}), default mapping already assigned.", type.getName());
        }
    }

    static class ObjectFactoryDelegateFactory implements Factory {

        String name;
        Class type;

        ObjectFactoryDelegateFactory(String name, Class type) {
            this.name = name;
            this.type = type;
        }

        public Object create(Context context) throws Exception {
            ObjectFactory objFactory = context.getContainer().getInstance(ObjectFactory.class);
            try {
                return objFactory.buildBean(name, null, true);
            } catch (ClassNotFoundException ex) {
                throw new ConfigurationException(String.format("Unable to load bean %s (name = %s)", type.getName(), name));
            }
        }

        @Override
        public Class type() {
            return type;
        }
    }
}
