package de.kilobyte22.app.kibibyte.plugin;
import de.kilobyte22.app.kibibyte.Kibibyte;
import de.kilobyte22.app.kibibyte.events.DisableEvent;
import de.kilobyte22.app.kibibyte.events.EnableEvent;
import de.kilobyte22.app.kibibyte.events.PluginDisableEvent;
import de.kilobyte22.app.kibibyte.events.PluginEnableEvent;
import de.kilobyte22.app.kibibyte.exceptions.InvalidPluginException;
import de.kilobyte22.lib.event.EventBus;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
/**
* Created with IntelliJ IDEA.
* User: Stephan
* Date: 07.03.13
* Time: 14:24
*
* @author Stephan
* @copyright Copyright 2013 Stephan
*/
public class Plugin {
private IPlugin plugin;
private URLClassLoader loader;
private Kibibyte bot;
private boolean enabled = false;
private String name;
private BotAccess botAccess;
private EventBus eventBus;
private EventBus.LockController eventBusLock;
public Plugin(File plugin, Kibibyte bot) throws IOException, ClassNotFoundException, InvalidPluginException, IllegalAccessException, InstantiationException {
this.bot = bot;
JarFile jf = new JarFile(plugin);
Attributes attrib = jf.getManifest().getMainAttributes();
String name = attrib.getValue("kibi-plugin-name");
String mainclass = attrib.getValue("kibi-plugin-class");
loader = new URLClassLoader(new URL[]{plugin.toURI().toURL()});
try {
Class<?extends IPlugin> pclass = (Class<? extends IPlugin>) Class.forName(mainclass, true, loader);
this.plugin = pclass.newInstance();
botAccess = new BotAccess(this.bot, this);
this.plugin.onLoad(botAccess);
this.name = name;
} catch (ClassCastException ex) {
throw new InvalidPluginException("Main class not found");
}
}
public Plugin(String clazz, Kibibyte bot, String name) throws IllegalAccessException, InstantiationException, ClassNotFoundException, InvalidPluginException {
this.bot = bot;
try {
Class<?extends IPlugin> pclass = (Class<? extends IPlugin>) Class.forName(clazz);
plugin = pclass.newInstance();
botAccess = new BotAccess(this.bot, this);
plugin.onLoad(botAccess);
this.name = name;
} catch (ClassCastException ex) {
throw new InvalidPluginException("Main class not found");
}
}
public void setEventBus(EventBus eventBus) {
this.eventBusLock = eventBus.new LockController();
this.eventBus = eventBus;
}
public void enable() {
enabled = true;
eventBus.postLocal(new EnableEvent());
eventBus.post(new PluginEnableEvent(name));
botAccess.commandManager.setEnabled(true);
}
public void disable() {
enabled = false;
eventBus.postLocal(new DisableEvent());
eventBus.post(new PluginDisableEvent());
botAccess.commandManager.setEnabled(false);
}
//public void load(Kibibyte bot) {plugin.onLoad(bot);}
public void unload() {
if (enabled) disable();
plugin.onUnload();
}
public String getName() {
return name;
}
}