package org.systemsbiology.infocore.namegrabber;

import ding.view.NodeContextMenuListener;
import giny.view.NodeView;

import javax.swing.*;
import cytoscape.Cytoscape;
import cytoscape.data.CyAttributes;

import java.util.List;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/**
 * User: dtenenba
 * Date: Nov 27, 2006
 * Time: 1:47:07 PM
 */
public class PreferredAliasChanger implements NodeContextMenuListener, ActionListener {

    private static PreferredAliasChanger _instance;

    private PreferredAliasChanger(){}

    public static synchronized PreferredAliasChanger getInstance() {
        if (_instance == null) {
            _instance = new PreferredAliasChanger();
        }
        return _instance;
    }


    public void addNodeContextMenuItems(NodeView nodeView, JPopupMenu jPopupMenu) {
        jPopupMenu.add(new JMenuItem("Debug"));
        String id = nodeView.getNode().getIdentifier();
        String[] attrNames = Cytoscape.getNodeAttributes().getAttributeNames();
        for (String attrName : attrNames) {
            byte attrType= Cytoscape.getNodeAttributes().getType(attrName);
            if (attrType != CyAttributes.TYPE_STRING) {
                continue;
            }
            String attrValue = Cytoscape.getNodeAttributes().getStringAttribute(id,attrName);
            if (attrName.equals("canonicalName")) {
                continue;
            }
            if (attrValue != null && !attrValue.trim().equals("")) {
                List<String> synonyms = getListAttributes(id, attrName);
                if (synonyms == null || synonyms.size() < 2)continue;

                JMenu menu = new JMenu("Change Display Synonym for " + nodeView.getLabel().getText());
                for (String synonym : synonyms) {
                    JCheckBoxMenuItem item = new JCheckBoxMenuItem(synonym,
                            synonym.equals(attrValue));
                    item.setActionCommand("attrName##"+attrName+"##attrValue##"+synonym+"##id##"+id);
                    item.addActionListener(this);
                    menu.add(item);
                }
                jPopupMenu.add(menu);

                break;
            }
        }
    }

    @SuppressWarnings("unchecked")
    private List<String> getListAttributes(String id, String attrName) {
        return (List<String>) Cytoscape.getNodeAttributes().getListAttribute(id, attrName + " Aliases");
    }

    /**
     * Invoked when an action occurs.
     */
    public void actionPerformed(ActionEvent e) {
        if (!e.getActionCommand().startsWith("attrName##"))return;
        //string is e.g. attrName##go##attrValue##GO:0005634##id##YAL005C
        String[] segs = e.getActionCommand().split("##");
        Cytoscape.getNodeAttributes().setAttribute(segs[5],segs[1],segs[3]);
        Cytoscape.getCurrentNetworkView().redrawGraph(false,false);
    }
}
