package de.renew.plugin;

import java.io.PrintStream;
import java.net.URL;
import java.net.URLClassLoader;

import de.renew.plugin.command.CLCommand;


/**
 * This ClassLoader is responsible for loading the classes
 * of non-modular plugins.
 * <br>
 * It allows adding classpath items dynamically.
 */
public class PluginClassLoader extends URLClassLoader {
    /**
     * Logger for logging purposes as specified by Apache Log4j
     */
    public static final org.apache.log4j.Logger LOGGER =
        org.apache.log4j.Logger.getLogger(PluginClassLoader.class);

    /**
     * Constructor for classloader responsible for loading non-modular plugins
     * @param parent Classloader to be used for loading plugins
     */
    public PluginClassLoader(ClassLoader parent) {
        super(new URL[0], parent);
    }

    /**
     * Add the given URL to the list where classes are sought for.
     */
    @Override
    public void addURL(URL url) {
        LOGGER.debug(this + " adding URL " + url);
        super.addURL(url);
    }

    class PackageCountCommand implements CLCommand {

        @Override
        public void execute(String[] args, PrintStream response) {
            String prefix = "";
            if (args.length != 0) {
                prefix = args[0];
            }
            Package[] packages = Package.getPackages();
            int count = 0;
            for (int i = 0; i < packages.length; i++) {
                if (packages[i].getName().startsWith(prefix)) {
                    response.println(packages[i]);
                    count++;
                }
            }
            response.println(count + " packages found.");
        }

        /*
         * @see de.renew.plugin.command.CLCommand#getDescription()
         */
        @Override
        public String getDescription() {
            return "prints the number of packages in the class loader";
        }

        @Override
        public String getArguments() {
            return null;
        }
    }
}