package de.renew.lola2;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Iterator;

import CH.ifa.draw.DrawPlugin;
import CH.ifa.draw.application.MenuManager;
import CH.ifa.draw.application.VersionInfoCommand;
import CH.ifa.draw.util.CommandMenu;
import de.renew.draw.storables.api.StorableApi;
import de.renew.lola2.commands.CheckAllCommand;
import de.renew.lola2.commands.CheckAllTasksCommand;
import de.renew.lola2.commands.CheckLivenessCommand;
import de.renew.lola2.commands.CheckSelectedPlaceCommand;
import de.renew.lola2.commands.CheckSelectedTransitionCommand;
import de.renew.lola2.commands.CheckVerificationRequestCommand;
import de.renew.lola2.commands.OpenLolaGUICommand;
import de.renew.lola2.io.LolaExportFormat;
import de.renew.lola2.io.LolaImportFormat;
import de.renew.plugin.IPlugin;
import de.renew.plugin.PluginAdapter;
import de.renew.plugin.PluginException;
import de.renew.plugin.PluginManager;
import de.renew.plugin.PluginProperties;


/**
 * This is a generated file. Generated by PluginDevelopment
 * plugin (version ${pd.version})
 * Representative for the Lola plug-in.
 *
 * @author PluginGenerator
 */
public class LolaPlugin extends PluginAdapter {
    //private StringBuffer lolaimages;
    private CommandMenu _menu;
    private LolaExportFormat _lolaExportFormat;
    private LolaImportFormat _lolaImportFormat;
    private static StringBuffer _lolaPath = new StringBuffer();
    private static org.apache.log4j.Logger _logger =
        org.apache.log4j.Logger.getLogger(LolaPlugin.class);

    //private File tmpDir = null;

    /**
     * Constructor for LolaPlugin.
     *
     * @param url the URL of the plugin
     * @throws PluginException if an error occurs during plugin initialization
     */
    public LolaPlugin(URL url) throws PluginException {
        super(url);
        //    registerClasses();
    }

    /**
     * Constructor for LolaPlugin.
     *
     * @param props the properties of the plugin
     */
    public LolaPlugin(PluginProperties props) {
        super(props);
        //    registerClasses();
    }

    /* (non-Javadoc)
     * @see de.renew.plugin.PluginAdapter#cleanup()
     */
    @Override
    public boolean cleanup() {
        DrawPlugin current = DrawPlugin.getCurrent();
        if (current == null) {
            return true;
        }
        StorableApi.removeExportFormat(_lolaExportFormat);
        StorableApi.removeImportFormat(_lolaImportFormat);

        MenuManager mm = current.getMenuManager();

        if (mm != null && _menu != null) {
            mm.unregisterMenu(_menu);
        }
        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see de.renew.plugin.PluginAdapter#getAlias()
     */
    @Override
    public String getAlias() {
        return "lola";
    }

    /* (non-Javadoc)
     * @see de.renew.plugin.PluginAdapter#init()
     */
    @Override
    public void init() {
        DrawPlugin current = DrawPlugin.getCurrent(); //needed for "Extras/Lola Integration" menu

        //        lolaimages.append(mylocation.substring(0, mylocation.lastIndexOf("dist")));
        //        lolaimages.append("Lola"+separator);

        //        CPNTextTool tool = new CPNTextTool(drawingEditor, new DeclarationFigure(), false);
        //        String imgFile = lolaimages.toString() + "LDECL.gif";
        //        logger.info("Toolbutton image is: "+imgFile);
        //        ToolButton fDeclTB = ((DrawApplication) drawingEditor).createToolButton(imgFile, "Lola Declaration Tool", tool);
        //        Palette palette =  new Palette(menuFrame, "Lola Tools");
        //        palette.add(fDeclTB);
        //
        //        ((DrawApplication) drawingEditor).getToolsPanel().add(palette.getComponent());
        StorableApi.addExportFormat(_lolaExportFormat = new LolaExportFormat());
        StorableApi.addImportFormat(_lolaImportFormat = new LolaImportFormat());

        if (current == null) {
            return;
        }
        if (_logger.isDebugEnabled()) {
            _logger.debug("[Lola] Plugin Name: " + _properties.getName());
        }
        if (_logger.isDebugEnabled()) {
            _logger.debug("[Lola] Plugin Location: " + _properties.getURL());
        }

        String mylocation = _properties.getURL().getPath();
        try {
            mylocation = URLDecoder.decode(_properties.getURL().getPath(), "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            _logger.warn("[Lola] could not decode location of Lola plugin.");
        }
        String separator = System.getProperty("file.separator");
        _lolaPath
            .append((mylocation.substring(0, mylocation.lastIndexOf("/"))).replace("%20", " "));
        _lolaPath.append(separator + "lib" + separator);
        if (_logger.isDebugEnabled()) {
            _logger.debug("[Lola] computed lib path: " + _lolaPath.toString());
        }

        MenuManager mm = current.getMenuManager();
        _menu = new CommandMenu("Lola2 Integration");
        _menu.add(new OpenLolaGUICommand("Show Lola GUI", _lolaPath.toString()));
        // export already captured by export format holder, no need for additional place
        //_menu.add(new ExportToLolaCommand("export net"));
        _menu.add(new CheckAllTasksCommand("Check all verification tasks", _lolaPath.toString()));
        _menu.add(
            new CheckVerificationRequestCommand("Check selected request", _lolaPath.toString()));
        _menu.add(
            new CheckSelectedTransitionCommand("Check selected Transitions", _lolaPath.toString()));
        _menu.add(new CheckSelectedPlaceCommand("Check selected Places", _lolaPath.toString()));
        _menu.add(new CheckAllCommand("Check all places and transitions", _lolaPath.toString()));
        _menu.add(new CheckLivenessCommand("Check liveness", _lolaPath.toString()));
        _menu.add(new VersionInfoCommand(this));
        _menu.putClientProperty(MenuManager.ID_PROPERTY, "de.renew.lola");
        mm.registerMenu(DrawPlugin.TOOLS_MENU, _menu);
    }

    /**
     * Returns the path of Lola
     *
     * @return lolapath
     */
    static public String getLolaPath() {
        return _lolaPath.toString();
    }

    /**
     * Returns the current running instance of LolaPlugin
     *
     * @return the current LolaPlugin instance
     */
    public static LolaPlugin getCurrent() {
        Iterator<IPlugin> plugins =
            PluginManager.getInstance().getPluginsProviding("de.renew.lola").iterator();
        while (plugins.hasNext()) {
            Object plugin = plugins.next();
            if (plugin instanceof LolaPlugin) {
                return (LolaPlugin) plugin;
            }
        }
        return null;
    }
}
