package de.renew.console.completer;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import jline.console.completer.Completer;
import jline.console.completer.StringsCompleter;

import de.renew.plugin.IPlugin;
import de.renew.plugin.PluginManager;
import de.renew.util.StringUtil;


/** Offers completions for plugin jar files.
 *
 * @author cabac
 *
 */
public class LocationsCompleter implements Completer {
    private static final org.apache.log4j.Logger LOGGER =
        org.apache.log4j.Logger.getLogger(LocationsCompleter.class);

    /**
     * Constructs a new {@code LocationsCompleter} instance with no specific initialization.
     */
    public LocationsCompleter() {}

    @Override
    public int complete(String buffer, int cursor, List<CharSequence> candidates) {
        return new StringsCompleter(getPluginLocations()).complete(buffer, cursor, candidates);
    }

    /**
     * Retrieves a list of file paths for all available plugins.
     * <p>
     * This method interacts with the {@link PluginManager} to fetch all registered plugins.
     * Each plugin's name is checked, and if a valid {@link IPlugin} instance is found,
     * its URL is formatted into a path string using {@link StringUtil#getExtendedFilename(String)}.
     * </p>
     * <p>
     * If a plugin cannot be found for a particular name, a debug message is logged.
     * </p>
     *
     * @return an {@code ArrayList} containing the file paths of all available plugins
     */
    public ArrayList<String> getPluginLocations() {
        PluginManager pm = PluginManager.getInstance();
        ArrayList<String> locations = new ArrayList<String>();
        Iterator<IPlugin> it = pm.getPlugins().iterator();
        while (it.hasNext()) {
            IPlugin iPlugin = it.next();
            String pluginName = iPlugin.getName();
            IPlugin plugin = pm.getPluginByName(pluginName);
            if (plugin == null) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(
                        "[" + LocationsCompleter.class.getSimpleName()
                            + "]: Could not find plugin for name: " + pluginName);
                }
            } else {
                locations
                    .add(StringUtil.getExtendedFilename(plugin.getProperties().getURL().getFile()));
            }
        }
        return locations;
    }
}