package org.systemsbiology.infocore.namegrabber;

import cytoscape.plugin.CytoscapePlugin;
import cytoscape.Cytoscape;
import cytoscape.CytoscapeInit;
import cytoscape.util.CytoscapeAction;

import javax.swing.*;
import javax.xml.rpc.ServiceException;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;

import org.systemsbiology.SynonymServiceLocator;
import org.systemsbiology.SynonymServiceSoap;

/**
 * User: dtenenba
 * Date: Nov 21, 2006
 * Time: 1:38:05 PM
 */
public class NameGrabberPlugin extends CytoscapePlugin implements PropertyChangeListener {

    public NameGrabberPlugin() {
        Cytoscape.getPropertyChangeSupport().addPropertyChangeListener(this);
        addContextMenuListener();

        JMenu menu = Cytoscape.getDesktop().getCyMenus().getOperationsMenu();
        menu.add(new NameGrabberAction());
    }

    public void propertyChange(PropertyChangeEvent event) {
        //System.out.println("#####event name: " + event.getPropertyName());
        // this is kind of ridiculous, but, let's re-add our listener in response
        // to EVERY EVENT that we catch. It can't hurt and it makes sure
        // our context menu is always available.
        addContextMenuListener();
    }

    private void addContextMenuListener() {
        if (Cytoscape.getCurrentNetworkView() != null) {
            Cytoscape.getCurrentNetworkView().removeNodeContextMenuListener(PreferredAliasChanger.getInstance());
            Cytoscape.getCurrentNetworkView().addNodeContextMenuListener(PreferredAliasChanger.getInstance());
        }
    }

    class NameGrabberAction extends CytoscapeAction {
        public NameGrabberAction() {
            super("Get Aliases...");
        }

        public void actionPerformed(ActionEvent e) {
            addContextMenuListener();
            JFrame frame = Cytoscape.getDesktop();
            if (CytoscapeInit.getProperties().getProperty("synonymService")==null) {
                JOptionPane.showMessageDialog(frame, "Error: property 'synonymService' not defined.");
                return;
            }


            SynonymServiceLocator ss = new SynonymServiceLocator();
            ss.setSynonymServiceSoapEndpointAddress(
              CytoscapeInit.getProperties().getProperty("synonymService"));

            try {
                SynonymServiceSoap synonym = ss.getSynonymServiceSoap();
                NameGrabberDialog gui = new NameGrabberDialog(frame.getGraphicsConfiguration());
                gui.setSynonymService(synonym);
                gui.setVisible(true);
            }
            catch (ServiceException ex) {
                ex.printStackTrace();
            }
        }
    }
}
