/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package blok.shell;

import blok.interfaces.IPlugin;
import blok.interfaces.IPluginController;
import blok.interfaces.ISimulator;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author aluno
 */
public class PluginController implements IPluginController {

    PluginController() {
        m_loadedPlugins = new ArrayList<IPlugin>();
    }

    @Override
    public boolean initialize() {
        File currentDir = new File("./plugins");
        String []plugins = currentDir.list();
        URL[] jars = new URL[plugins.length];
        for (int i = 0; i < plugins.length; i++) {
            try {
                jars[i] = (new File("./plugins/" + plugins[i])).toURL();
            } catch (MalformedURLException ex) {
                Logger.getLogger(PluginController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        URLClassLoader ucl = new URLClassLoader(jars);
        for (String pluginName : plugins) {
            String factoryName = pluginName.split("\\.")[0];
            IPlugin plugin = null;
            try {
                plugin = (IPlugin) Class.forName("blok.plugin." + factoryName, true, ucl).newInstance();
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(PluginController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                Logger.getLogger(PluginController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(PluginController.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (plugin != null) {
                plugin.initialize();
                m_loadedPlugins.add(plugin);
            }
        }
        
        System.out.println("Carreguei " + m_loadedPlugins.size() + " plugins!");
        System.out.println("Carreguei " + this.getLoadedPluginsByType(ISimulator.class).size() + " plugins de simulator!");
        return true;
    }

    @Override
    public ArrayList<IPlugin> getLoadedPlugins() {
        return m_loadedPlugins;
    }

    @Override
    public ArrayList<IPlugin> getLoadedPluginsByType(Class type) {
        ArrayList<IPlugin> loadedPluginsByType = new ArrayList<IPlugin>();
        for (IPlugin plugin : m_loadedPlugins)
            if (type.isInstance(plugin))
                loadedPluginsByType.add(plugin);
        return loadedPluginsByType;
    }

    private ArrayList<IPlugin> m_loadedPlugins;
}
