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;


/**
 *  This class implements the Completer interface and
 *  provides auto-completion for plugin names retrieved from the PluginManager.
 *  It formats the names by trimming whitespace and replacing spaces with underscores
 *  to ensure consistent suggestions.
 * @author cabac
 *
 */
public class PluginCompleter implements Completer {
    /**
     * Constructs a new {@code PluginCompleter}.
     */
    public PluginCompleter() {}

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

    /**
     * Retrieves a list of plugin names from the {@link PluginManager} instance.
     * Each plugin name is trimmed of any leading or trailing whitespace and
     * spaces are replaced with underscores for uniformity in completion.
     *
     * @return an {@code ArrayList} containing the formatted plugin names
     */
    public ArrayList<String> getPluginNames() {
        PluginManager pm = PluginManager.getInstance();
        ArrayList<String> pNames = new ArrayList<String>();
        Iterator<IPlugin> it = pm.getPlugins().iterator();
        while (it.hasNext()) {
            String pluginName = it.next().getName();
            pNames.add(pluginName.trim().replaceAll(" ", "_"));
        }
        return pNames;
    }
}