package com.atlassian.stash.internal.plugin;

import com.atlassian.plugin.Plugin;
import com.atlassian.plugin.hostcontainer.HostContainer;
import com.atlassian.plugin.module.ContainerManagedPlugin;
import com.atlassian.plugin.web.Condition;
import com.atlassian.plugin.web.conditions.ConditionLoadingException;
import com.atlassian.plugin.web.descriptors.ConditionElementParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Loads {@link Condition} elements from module descriptors.
 *
 * Based on the anonymous implementation in {@link com.atlassian.plugin.webresource.WebResourceModuleDescriptor}.
 */
@Component
public class StashConditionFactory implements ConditionElementParser.ConditionFactory {

    private final HostContainer hostContainer;

    @Autowired
    public StashConditionFactory(HostContainer hostContainer) {
        this.hostContainer = hostContainer;
    }

    public Condition create(String className, Plugin plugin) throws ConditionLoadingException {
        try {
            Class<Condition> conditionClass = plugin.loadClass(className, this.getClass());
            if (plugin instanceof ContainerManagedPlugin) {
                return ((ContainerManagedPlugin) plugin).getContainerAccessor().createBean(conditionClass);
            } else {
                return hostContainer.create(conditionClass);
            }
        } catch (ClassNotFoundException e) {
            throw new ConditionLoadingException("Cannot load condition class: " + className, e);
        }
    }

}
