/*
   Tamot --- Task Modelling Editor
   Copyright (C) 2000 Commonwealth Scientific and Industrial Research Organisation
   (CSIRO), Australia. All rights reserved. 

   The Software, owned by CSIRO Australia, has been developed by the CSIRO 
   Intelligent Interactive Technology group. 
   For more information, please see http://www.cmis.csiro.au/iit/.

   The Software is a beta-test version for internal research and evaluation purposes 
   by the Licensee. The Software is still at a development stage. 
   It has not undergone complete testing and may have inherent errors,
   bugs or deficiencies that can affect the operation of the Software. 

   We encourage your feedback and suggestions. Any bugs / suggestions found please email to
   Shijian.Lu@cmis.csiro.au and Thomas.Lo@cmis.csiro.au. 

   After you have signed the Beta-Test Software License Agreement with the CSIRO,
   CSIRO grants you a non-exclusive, non-transferable license to use it only for your 
   personal, non-commercial and lawful end use. Implied licenses are negated. 

   Warranty Disclaimer : 

   CSIRO supplies the Software on an "as is" basis and makes no warranties that use of
   the Software by the Licensee will not infringe any third party’s 
   Intellectual Property Rights nor that the Software will be of merchantable quality,
   or suitable for a particular purpose. CSIRO excludes all terms, conditions and
   warranties implied by custom, the general law or statute in relation to the
   Software.
*/

package domainModel.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.metal.MetalComboBoxButton;
import javax.swing.event.*;
import java.util.*;
import java.io.*;
import domainModel.*;
import taskModellingTool.*;
import utility.*;


public class ActionPane extends JPanel {
	
  	private DmManager _dMM=Manager.getXDM().getDmManager();	// default _dMM 
 	private static DmRelation _dMRelat = DmRelation.getInstance();
	private ActionInstance _aIns; 		//selected action instance
	private DmEdit _owner; 		//owner of this Jpanel
	
	private boolean _modified= false; 		//for monitoring user modification
	private boolean _conModified= false; 		//for monitoring concept cahnge	//private Color _textColor=DmManager 		
	
	//define dimension for the list box
	private static int NUMBER_OF_ROWS = 8;	//used by the Jlists
	private static int CELL_WIDTH = 237;	//used by the Jlists
	
	//define labels to be used in the dialod box 
	private static final JLabel _name = new JLabel("Name");
	private static final JLabel _concept =new JLabel( "Concept");
	private static final JLabel _prem = new JLabel("Premodifier");
	private static final JLabel _postm =new JLabel( "Postmodifier");
	private static final JLabel _note = new JLabel("Comment");
	
	private JPanel _rootPanel, _actPanel,_relnsPanel,_insPanel;
	private JList _actL;
	private JLabel _mainLabel=new JLabel("Action Instance");

	// put all entity concepts(including User and System types in _concepts
   	private JComboBox _conCm = new JComboBox();
	private JTabbedPane _tabPane;
	
	private DefaultListModel _model; //for holding action list content
  	private HashMap _indxIDAct; 	//   HashMap for pairs of index and ID 
  											//for Action instance
  	private HashMap _idIndxAct; 	//   HashMap for pairs of index and 

  	private HashMap _indxIDRel; 	//  nested HashMap for pairs of index and ID 
  											//for action-entity relation instance
  	private HashMap _idIndxRel; 	//  nested HashMap for pairs of index and 
  											//ID for action-entity relation instance
  	private HashMap _indxIDRelAA; 	//  nested HashMap for pairs of index and ID 
  											//for action-action relation instance
  	private HashMap _idIndxRelAA; 	//  nested HashMap for pairs of index and 
  											//ID for action-action relation instance
  	private HashMap _RelCombos=new HashMap();
									 	//   HashMap for pairs of relation-name
   											// and comboBox
   	//2001-8-16
  	//   HashMap for pairs of index and ID for act-concept 
  	private HashMap _indxIDcon; 
  	
	private HashMap _relLabels=new HashMap();
									 	//   HashMap for pairs of relation-name
  											// and labels
   	//define editable components
	private JTextField _nameT = new JTextField();
	private JTextField _premT = new JTextField();
	private JTextField _postmT = new JTextField();

   	//private JCheckBox _dirtyC;
   	private JTextArea _noteA = new JTextArea();
   
   	//define popup menu	)
   	private JPopupMenu _popMenu = new JPopupMenu();
   	//private JPopupMenu _popList = new JPopupMenu();
  	private JMenuItem _actIn = new JMenuItem("Add New Action Instance");
  
  	private JMenuItem _editIn = new JMenuItem("Edit");
  	private JMenuItem _deleteIn = new JMenuItem("Delete");
  	private JMenuItem _reset = new JMenuItem("Reset");
   	private JMenuItem _filter = new JMenuItem("Filter");
    private JMenuItem _color = new JMenuItem("Set Color");
  	private JMenuItem _colorDefault = new JMenuItem("Change to Default Color");
  	//31-10-2001
  	private JMenuItem _deleteRelatedEnIns = 
  		new JMenuItem("Delete (+ related entity instances)");
  		
  	//16-1-2002
  	// add popup JCheckBoxMenuItem to action-entity relation
      // instance to specify contextual-types
    private ButtonGroup _bgroup = new ButtonGroup();
    private JPopupMenu _popMenuContextType = new JPopupMenu();
    
    //17-1-2002
    private String _currentActEntityRelation= null;
    private HashMap _combosRel=new HashMap();
					//   HashMap for pairs of comboBox 
   					//   and relation-name
   	public ActionPane(DmEdit owner){
		super();
        //_popMenu.add(_popNew);    
		_owner = owner;

		addMenuItemListener();
		addModifyListener();
		add(getRootPanel());
		setTextColor(DmManager.getActColor());
		
		//16-1-2002
		//initialise conrtextual Type popup-menu
		initContextTypeMenu();
	}
	
	private void addMenuItemListener(){
	   _actIn.addActionListener(new java.awt.event.ActionListener() {
	      	public void actionPerformed(ActionEvent e) {
	        	_dMM.newAIns();
				updateTab();
	      	}
	    });
    
	   _editIn.addActionListener(new java.awt.event.ActionListener() {
	      	public void actionPerformed(ActionEvent e) {
	      		editIns();
	      	}
	    });
    
	   _deleteIn.addActionListener(new java.awt.event.ActionListener() {
	      	public void actionPerformed(ActionEvent e) {
				deleteIns();	      
	      	}
	    });
    
	   _deleteRelatedEnIns.addActionListener(new java.awt.event.ActionListener() {
	      	public void actionPerformed(ActionEvent e) {
				deleteRelatedIns();	      
	      	}
	    });
    
	   _reset.addActionListener(new java.awt.event.ActionListener() {
	      	public void actionPerformed(ActionEvent e) {
				resetTabs();
	      	}
	    });
	    
	   _filter.addActionListener(new java.awt.event.ActionListener() {
	      	public void actionPerformed(ActionEvent e) {
				_owner.actFilter(_aIns);
	      	}
	    });

		_color.addActionListener(new java.awt.event.ActionListener() {
	      	public void actionPerformed(ActionEvent e) {
				setColor();
	      	}
	    });

		_colorDefault.addActionListener(new java.awt.event.ActionListener() {
	      	public void actionPerformed(ActionEvent e) {
				setColorDefault();
	      	}
	    });
    

	}
	
    private void addModifyListener(){
    	_nameT.addKeyListener(new KeyAdapter() {
      		public void keyReleased(KeyEvent ke) {
      			setModified(true);
				updateName(_nameT.getText());
      		}
		});

		_premT.addKeyListener(new KeyAdapter() {
      		public void keyReleased(KeyEvent ke) {
      			setModified(true);

      		}
		});
		
     	_postmT.addKeyListener(new KeyAdapter() {
      		public void keyReleased(KeyEvent ke) {
      			setModified(true);

      		}
		});
   	
     	_noteA.addKeyListener(new KeyAdapter() {
      		public void keyReleased(KeyEvent ke) {
      			setModified(true);

      		}
		});
    	
    	_conCm.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
      			setModified(true);
      			_conModified = false;
	    		//System.out.println("concept item changeed" );
		}
		});

   }
    
    private void setModified(boolean bo){
    	_modified = bo;
    	//System.out.println("called set modified " + bo);
    	return;
    }
    
	private void deleteIns(){
		//remove semantics from relevant tasks
		Manager.removeSemantics(_dMM.findTaskAIns(_aIns));
		
		//now remove the action instance
		_dMM.removeAInstance(_aIns); 
		
		//update list
		updateTab();
	}
	
	private void updateTab(){
		setJlistContent(_dMM.getAInstanceAll());
	}
	
	private void editIns(){
		if (_aIns != null){
			AInstanceEdit id = new AInstanceEdit(MainFrame.getMainFrame(),
				"Edit Action Instance",_aIns);
		}
	}
	
	private void resetTabs(){
		updateTab();
	}
	
	private JPanel getRootPanel(){
		_rootPanel= new JPanel();
		//Dimension PanelD= new Dimension(200,100);
		
       	_rootPanel.setLayout(new BorderLayout());
     	_rootPanel.add(getTopPanel(),BorderLayout.NORTH);
    	_rootPanel.add(getInsPanel(),BorderLayout.CENTER);
      	_rootPanel.setPreferredSize(_rootPanel.getPreferredSize());
		return _rootPanel;	
	}
	
	private JPanel getTopPanel(){
		JPanel topP = new JPanel();
       	topP.setLayout(new BorderLayout());
		//lab.setForeground(DmManager.getActColor());  
		
		topP.add(_mainLabel,BorderLayout.NORTH);
     	topP.add(getTabPanel(),BorderLayout.CENTER);
     	return topP;
	}
	
	private JTabbedPane getTabPanel(){
		_tabPane= new JTabbedPane();
		// Add the different tabs 
		_tabPane.addTab("action",	//DmConcept.getDefaultActionConcept().getName(),
			null, getActTab());
		_tabPane.setForeground(DmManager.getActColor());    
		
		//add listener
		_tabPane.addChangeListener(tabListener);
	/*	
		Rectangle rect = new Rectangle(0,17, 218,194);
		_tabPane.setBounds(rect);
		_tabPane.setSize(218, 194);	//getPreferredSize());
	*/	
     	return _tabPane;	
      
	}
	
	ChangeListener tabListener = new ChangeListener(){
		public void stateChanged(ChangeEvent e) {			
			// save change, if any
			storeChange();
			setModified(false); 
			selectAct();

		}
	};
	
	private JPanel getActTab(){
		_actPanel= new JPanel();
		_actL = new JList();
		setJlistContent(_dMM.getAInstanceAll());
			
		//_actPanel.add(_actL);
		
		JScrollPane scrollP= new JScrollPane(_actL);
     	scrollP.setHorizontalScrollBarPolicy(
          JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);	//	_NEVER);
     	scrollP.setVerticalScrollBarPolicy(
          JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
			
		_actPanel.add(scrollP);
		_actL.setVisibleRowCount(NUMBER_OF_ROWS);
		_actL.setFixedCellWidth(CELL_WIDTH);

		_actL.addListSelectionListener(actListener);
		
		_actL.addMouseListener(mosueListener);		
		//_actPanel.addMouseListener(popupListener);
		//_actPanel.setSize(_actPanel.getMinimumSize());	//getPreferredSize());

		return _actPanel;	
	}
	
	ListSelectionListener actListener = new ListSelectionListener(){
		public void valueChanged(ListSelectionEvent e) {
			storeChange();
			setModified(false); 

			selectAct();

		}
	};
	
	MouseListener mosueListener = new MouseAdapter(){
    	public void mousePressed(MouseEvent e) {
     		storeChange();
     		setModified(false); 

   			//enable right-mouse-button selection
    		int index = _actL.locationToIndex(e.getPoint());
    		_actL.setSelectedIndex(index);
    		
			selectAct();
			
			maybeShowPopup(e);
		}	
    	public void mouseClicked(MouseEvent e) {
			//if click more than once, invoke filter
			if (e.getClickCount() > 1)
				_owner.actFilter(_aIns);
		}	

		public void mouseReleased(MouseEvent e) {
		  	maybeShowPopup(e);
		}
		
		public void maybeShowPopup(MouseEvent e) {
			
			if (e.isPopupTrigger()) {
		      	//System.out.println( "\n right mouse button pressed");
				constructMenu();
		        _popMenu.show(e.getComponent(),
		        e.getX(), e.getY());
		    }
		}

	};
	
	private void constructMenu(){
		_popMenu.removeAll();    
		_popMenu.add(_actIn);
		if (_aIns == null){
	        _popMenu.add(new JPopupMenu.Separator());  
			_popMenu.add(_color);  
			_popMenu.add(_colorDefault);  
	        _popMenu.add(new JPopupMenu.Separator());  
			_popMenu.add(_reset);  
		
		}else{
	        _popMenu.add(new JPopupMenu.Separator());    
		//	_popMenu.add(_editIn);
			_popMenu.add(_deleteIn);    
			_popMenu.add(_deleteRelatedEnIns);    
			_popMenu.add(_filter);
	        _popMenu.add(new JPopupMenu.Separator());    
			_popMenu.add(_color);  
			_popMenu.add(_colorDefault);  
	        _popMenu.add(new JPopupMenu.Separator());  
			_popMenu.add(_reset);  
		}
		return;	
	}
 
	private void selectAct(){
		//String aiName = (String)_actL.getSelectedValue();
		//updateIns(aiName); Integer.toString
		
		int i = _actL.getSelectedIndex();
		String iD = (String)_indxIDAct.get(Integer.toString(i));
		updateIns(iD);

	}
	
	
	public void updateIns(String aiID){
		if (aiID == null || aiID.equals("")){
			setFieldsContent(null);
			setRelationContent(null);
			_aIns = null;
		} else {
			ActionInstance ai = _dMM.getAInstance(aiID);
			_aIns = ai;
			if (ai == null) return;
			setFieldsContent(ai);
			setRelationContent(ai);
		}
		//refresh();
	}
	/*
	public void updateIns(String aiName){
		if (aiName == null || aiName.equals("")){
			setFieldsContent(null);
			setRelationContent(null);
			_aIns = null;
		} else {
			ActionInstance ai = _dMM.getAInstanceByName(aiName);
			_aIns = ai;
			if (ai == null) return;
			setFieldsContent(ai);
			setRelationContent(ai);
		}
		//refresh();
	}
	*/
	
	/** remove all content for list if there is any,
	* then populate list with action _actL
	*/
	public void setJlistContent( Collection action ){
		JList list=_actL;
		list.removeAll(); 
		Iterator it = action.iterator();
		ActionInstance ai;
		_model = new DefaultListModel();
		_indxIDAct = new HashMap();
		_idIndxAct = new HashMap();
		int i =0;
		while (it.hasNext()){
			ai = (ActionInstance)it.next();
			_model.addElement(ai.getName());
			
	      	_indxIDAct.put(Integer.toString(i),ai.getID() );
	      	_idIndxAct.put(ai.getID(),Integer.toString(i++) );
		}
		list.setModel(_model);
		return;	
	}

	private JPanel getInsPanel(){
		if (_insPanel!= null) return _insPanel;
		
		_insPanel= new JPanel();
       	_insPanel.setLayout(new BorderLayout());
     	//insPanel.setLayout(new GridLayout(3,1));
       	_insPanel.add(getFieldsPanel(),BorderLayout.NORTH);
      	_insPanel.add(getRelationPanel(),BorderLayout.CENTER);
     	_insPanel.add(getNotePanel(),BorderLayout.SOUTH);
		return _insPanel;	
	}

	private JPanel getFieldsPanel(){
		JPanel fieldsPanel= new JPanel();
		
      	fieldsPanel.setLayout(new GridLayout(6,2));
      	//add 1 empty row
      	fieldsPanel.add(new JLabel());
      	fieldsPanel.add(new JLabel(" "));

      	fieldsPanel.add(_name);
     //	_nameT = new JTextField();
      	fieldsPanel.add(_nameT);
      
      	//initialize concept Combon box
      	fieldsPanel.add(_concept);
      //	_conCm = new JComboBox();
	  	fieldsPanel.add(_conCm);
//	fieldsPanel.add(new JLabel(_cardinality));
      //	_cardCm = new JComboBox();
      //	fieldsPanel.add(_cardCm);
		
      	fieldsPanel.add(_prem);
     //	_premT = new JTextField(); 	//_aIns.getPreModifier());
      	fieldsPanel.add(_premT);

      	fieldsPanel.add(_postm);
     //	_postmT = new JTextField(); 	//_aIns.getPostModifier());
      	fieldsPanel.add(_postmT);
		
     	return fieldsPanel;	
		
	}
	
	public void setFieldsContent(ActionInstance ai){
		if (ai == null)
			clearFieldsContent();
		else{
			//clearFieldsContent();
			
			_nameT.setText(ai.getName());
			
			DefaultComboBoxModel mod1= new DefaultComboBoxModel();
			Iterator it = _dMM.getActionCons().iterator();
				//	_dMM.getConceptSome(
					//ConceptType.getDefaultActionType()).iterator();
			int i = 0;
			DmConcept con;
			_indxIDcon = new HashMap();
	      	while ( it.hasNext()) {
	      		con=(DmConcept)it.next();
	      		mod1.addElement(con.getName()+"-"+con.getType());
	      		_indxIDcon.put(Integer.toString(i++),con.getID() );
	      	}
      		_conCm.setModel(mod1);
			
      		if (ai.getConceptOf()!= null){ 
      			String ty= ai.getConceptOf().getName()+
					"-"+ai.getConceptOf().getType();
				//System.out.println("concept name: ===" + ty);
				_conCm.setSelectedItem(ty);
      		}	//else System.out.println("no action concept");
			
		//	DefaultComboBoxModel mod= new DefaultComboBoxModel(
		//			EntityInstance.getCardinalityAll());
      	//	_cardCm.setModel(mod);
   		//	_cardCm.setSelectedItem(ai.getCardinality());
   			
   			String pre = ai.getPreModifier();
   			if (pre == null || pre.equals(""))
				_premT.setText(" ");
			else 
				_premT.setText(pre);
				
   			String post = ai.getPostModifier();
   			if (post == null || post.equals(""))
				_postmT.setText(" ");
			else 
				_postmT.setText(post);
				
   			String note = ai.getNote();
   			if (note == null || note.equals(""))
				_noteA.setText(" ");
			else 
				_noteA.setText(note);
		
		}
		
		_conModified = false;
	}
	
	
	private void clearFieldsContent(){
		_nameT.setText(" ");
		DefaultComboBoxModel mod= new DefaultComboBoxModel();
		_conCm.setModel(mod);
	//	_cardCm.setModel(mod);
		_premT.setText(" ");
		_postmT.setText(" ");
		_noteA.setText(" ");
	}
	
	private JPanel getNotePanel(){
		JPanel notePanel= new JPanel();
		
		Dimension notePanelD= new Dimension(200,75);
      	notePanel.setPreferredSize(notePanelD);
      
      	notePanel.setLayout(new BorderLayout());
							//new GridLayout(2,1));
		
    	notePanel.add(_note,BorderLayout.NORTH);
     	_noteA.setLineWrap(true);
     	     	
     	JScrollPane scrollP= new JScrollPane(_noteA);
     	scrollP.setHorizontalScrollBarPolicy(
          JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
     	scrollP.setVerticalScrollBarPolicy(
          JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
          
      	notePanel.add(scrollP, BorderLayout.CENTER);
     	
      	//notePanel.add(_noteA, BorderLayout.CENTER);
      	
     	return notePanel;	
      
	}
	
	
	private JPanel getRelationPanel(){
		_relnsPanel= new JPanel();
   		_indxIDRel = new HashMap();
   		_idIndxRel = new HashMap(); 
		
   		_indxIDRelAA = new HashMap();
   		_idIndxRelAA = new HashMap(); 

   		String allEnRle[] = _dMRelat.getAllActionRelations();
      	int numberRel =allEnRle.length; 
   		String allAARle[] = _dMRelat.getAllActionActRelations();
      	int numberAARel =allAARle.length; 

      	_relnsPanel.setLayout(new GridLayout(numberRel+numberAARel,2));
      	
      	String relName;
      	JComboBox tempCm;
	//	TreeMap reEnInstances = _aIns.getEntityRelations();    
		for (int j = 0; j < numberRel; j++) {
			relName = allEnRle[j];
      		_indxIDRel.put(relName,new HashMap() );
      		_idIndxRel.put(relName,new HashMap() );
      		
      		JLabel tempL =new JLabel(relName);
      		_relLabels.put(relName,tempL);
      		
			_relnsPanel.add(tempL);
			tempCm =getEInsCm(relName);
			
     			//17-1-2002
    			//add contextType listner to the combobox
			new InstallMouseListener(tempCm, mosueListenerContext);

			_relnsPanel.add(tempCm);
		}
    	
		for (int j = 0; j < numberAARel; j++) {
			relName = allAARle[j];
      		_indxIDRelAA.put(relName,new HashMap() );
      		_idIndxRelAA.put(relName,new HashMap() );
      		
      		JLabel tempL =new JLabel(relName);
      		_relLabels.put(relName,tempL);
      		
			_relnsPanel.add(tempL);
			_relnsPanel.add(getEInsCm(relName));
		}
    	
    	return _relnsPanel;
      
	}
	
	public void setRelationContent(ActionInstance ai){
		_indxIDRel = new HashMap();
   		_idIndxRel = new HashMap(); 
   		_indxIDRelAA = new HashMap();
   		_idIndxRelAA = new HashMap(); 

   		String allEnRle[] = _dMRelat.getAllActionRelations();
      	int numberRel =allEnRle.length;
   		String allAARle[] = _dMRelat.getAllActionActRelations();
      	int numberAARel =allAARle.length; 
	    String relName;
	    
		if (ai == null){
			for (int j = 0; j < numberRel; j++) {
				relName = allEnRle[j];
				clearEiRelInsContent(relName);
	    	}
			for (int j = 0; j < numberAARel; j++) {
				relName = allAARle[j];
				clearAARelInsContent(relName);
	    	}
		}
		else{

			TreeMap reEnInstances = ai.getActionRelations();    
			for (int j = 0; j < numberRel; j++) {
				relName = allEnRle[j];
	      		_indxIDRel.put(relName,new HashMap() );
	      		_idIndxRel.put(relName,new HashMap() );;
				setEiRelInsContent(relName,
					(EntityInstance)reEnInstances.get(relName));
	    	}
			TreeMap aaInstances = ai.getActionActRelations();    
			for (int j = 0; j < numberAARel; j++) {
				relName = allAARle[j];
	      		_indxIDRelAA.put(relName,new HashMap() );
	      		_idIndxRelAA.put(relName,new HashMap() );
	      		
				setAAInsContent(relName,
					(ActionInstance)aaInstances.get(relName));
				
	    	}
		}
	}
	
	private JPanel getRelPanel(){
		JPanel _relnsPanel= new JPanel();
    	return _relnsPanel;
      
	}
	
	private JComboBox getEInsCm(String relName ){
    		/*final*/ JComboBox tempCm = new JComboBox();
    				
		tempCm.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
      			setModified(true);
      			//System.out.println("selected index= " +
      			//	tempCm.getSelectedIndex());

			}
		});

		tempCm.setForeground(DmManager.getActColor());    

		_RelCombos.put(relName,tempCm);
		
		//17-1-2002
		_combosRel.put(tempCm,relName);

		
		return tempCm;
	}
	
	public void setEiRelInsContent(String relName,EntityInstance en){
		JComboBox tempCm= (JComboBox)_RelCombos.get(relName);
		if ( tempCm == null)
			return;
			
	//    Iterator it = _dMM.getEInstanceAll().iterator();
	    EntityInstance temp ;
	   	HashMap tempInxId = (HashMap)_indxIDRel.get(relName );
	   	HashMap tempIdInx = (HashMap)_idIndxRel.get(relName );
	   	
		DefaultComboBoxModel mod= new DefaultComboBoxModel();
		
		// there is a bug in JCombobox for v1.2.2
		//when there are more than 1 items whare the 
		//same name, it is not possible to select items
		// other than the first ocurrence
		int j= 2; 
		String last ="";
		String current;
		
		int i= 1; 	// if no relation instance select "None"
		mod.addElement("");
	    Iterator it = _dMM.getEInstanceAll().iterator();
	    
	    // check if there are items with same name
      	while ( it.hasNext()) {
      		temp = (EntityInstance)it.next();
      		current = temp.getName();
      		if (!(last.equals(current))){
      			mod.addElement(current);
      			j=2;
      		} else {
      			mod.addElement(current + " ("+  j++ + ")");
      		}
      		
      		last = current;
	      	tempInxId.put(Integer.toString(i),temp.getID() );
	      	tempIdInx.put(temp.getID(),Integer.toString(i++) );
      	}
      	tempCm.setModel(mod);
      	
		i= 0; 	// if no relation instance select "None"
      	if (en != null)
      		i= Integer.parseInt((String)tempIdInx.get(en.getID()));
      		
      	tempCm.setSelectedIndex(i);

	    	      
		return;  	
	}
	
	public void clearEiRelInsContent(String relName){
		JComboBox tempCm= (JComboBox)_RelCombos.get(relName);
		if ( tempCm == null)
			return;
		DefaultComboBoxModel mod= new DefaultComboBoxModel();
  		tempCm.setModel(mod);	      	
	    	      
		return;  	
	}
	
	public void updateChange(){
		storeChange();
	}

	private void storeChange(){
		// update Enttity instance attributes
		if (_aIns == null) /*|| !(_modified))*/ return;
		
     	_aIns.setName(_nameT.getText());
     //	String ConceptName= (String)_conCm.getSelectedItem();
     //	if (_conModified ){
	     	int i = _conCm.getSelectedIndex();
			//System.out.println("conctent changed+ index="+i);
	     	String iD = (String)_indxIDcon.get(Integer.toString(i));
	     	_aIns.setConceptOf(_dMM.getAConcept(iD));
     //	}
     //	_aIns.setDirty(_dirtyC.isSelected());
     //	String cardi= (String)_cardCm.getSelectedItem();
     //	_aIns.setCardinality(cardi);
     	_aIns.setPreModifier(_premT.getText());
     	_aIns.setPostModifier(_postmT.getText());

     	_aIns.setNote(_noteA.getText());
        updateRel();
        updateAARel();

        setModified(false); 
		_conModified = false;
      //2001-2-14
      // mark related task dirty
      DmManager.getInstance().markTaskDirty(_aIns);
	}
	
	
	private void updateRel(){
      String allActRle[] = _dMRelat.getAllActionRelations();
      int numberRel =allActRle.length; 
      String relName;
	//	TreeMap reActInstances = _aIns.getEntityRelations();    
		for (int j = 0; j < numberRel; j++) {
			relName = allActRle[j];
			//get selected instance index
			JComboBox tempCm =(JComboBox)_RelCombos.get(relName);
			if (tempCm == null)
				continue;
			
			int indexSelect = tempCm.getSelectedIndex();
			
			if (indexSelect == 0){
				_aIns.setActionRelation(relName,null);
				continue;

			}
			//get selected instance ID
			HashMap tempHM= (HashMap) _indxIDRel.get(relName);
			String tempID  = (String)	tempHM.get(Integer.toString(indexSelect));
			//System.out.println( "\n realtion : "+ relName+ " index =" +indexSelect
			//			+ " ID =" + tempID);

			EntityInstance tempEn = _dMM.getEInstance(tempID);
			
			//update the content of the relation related instsance
			if (tempEn != null){
				_aIns.setActionRelation(relName,tempEn);
			}
    	}
    }
    
    public void setTextColor(Color co){
    	//_textColor = co;,  setColor
    	DmManager.setActColor(co);
    	setMenuItemColor( co);	
      	setLabelColor(co);
      	setActRelCol(co);
    	

		//Textfilds  
		_nameT.setForeground(co);    
		_conCm.setForeground(co);    
		_premT.setForeground(co);    
		_postmT.setForeground(co);
		
		_noteA.setForeground(co);    

		return;
    	
    }
    
    public void setActRelCol(Color co){
		//set act-entity relation color
      	String allActRle[] = _dMRelat.getAllActionRelations();
      	int numberRel =allActRle.length; 
      	String relName;
      	JComboBox tempCm;
      	JLabel tempL;
		for (int j = 0; j < numberRel; j++) {
			relName = allActRle[j];
			tempCm =(JComboBox)_RelCombos.get(relName);
			if (tempCm != null)
				tempCm.setForeground(co);
				
			tempL =(JLabel)_relLabels.get(relName);
			if (tempL != null)
				tempL.setForeground(co);
		}
		
		//set act-act relation color
   		String allAARle[] = _dMRelat.getAllActionActRelations();
      	int numberAARel =allAARle.length; 
		for (int j = 0; j < numberAARel; j++) {
			relName = allAARle[j];
			tempCm =(JComboBox)_RelCombos.get(relName);
			if (tempCm != null)
				tempCm.setForeground(co);
				
			tempL =(JLabel)_relLabels.get(relName);
			if (tempL != null)
				tempL.setForeground(co);
		}
      	
		return;
    }
   
    public void setLabelColor(Color co){
    	//labels
    	_mainLabel.setForeground(co);
    	_tabPane.setForeground(co);
 		_actL.setForeground(co);    
 		_name.setForeground(co);    
		_concept.setForeground(co);    
		_prem.setForeground(co);    
		_postm.setForeground(co);
		_note.setForeground(co);
		return;
    }
    public void setMenuItemColor(Color co){
		//popup meniItems
		_actIn.setForeground(co);    
		_editIn.setForeground(co);    
		_deleteIn.setForeground(co);    
		_deleteRelatedEnIns.setForeground(co);    
		_reset.setForeground(co);
		_filter.setForeground(co);    
		_color.setForeground(co);    
		_colorDefault.setForeground(co);
		return;
    }
    
    public void setColor(){
		Color color = JColorChooser.showDialog(MainFrame.getMainFrame(), 
			"Choose Color for Action Instance", DmManager.getActColor());    
		if (color == null)
   			return;
   			
    	setTextColor(color);
   		return;
   	
    }
    
    public void setColorDefault(){
    	setTextColor(DmManager.ACTION_COLOR);
   	
    }
    
    private void updateName(String name){
		int i = _actL.getSelectedIndex();
		_model.set(i, name);
   	
    }
    
    //31-10-2001
	private void deleteRelatedIns(){
		_dMM.removeAiAndEi(_aIns); 
		
		//update list
		updateTab();
	}
	

//14-11-2001   
//    clear action-action relation instance 
	public void clearAARelInsContent(String relName){
		JComboBox tempCm= (JComboBox)_RelCombos.get(relName);
		if ( tempCm == null)
			return;
		DefaultComboBoxModel mod= new DefaultComboBoxModel();
  		tempCm.setModel(mod);	      	
	    	      
		return;  	
	}
	
	public void setAAInsContent(String relName,ActionInstance ai){
		JComboBox tempCm= (JComboBox)_RelCombos.get(relName);
		if ( tempCm == null)
			return;
			
	//    Iterator it = _dMM.getEInstanceAll().iterator();
	    ActionInstance temp ;
	   	HashMap tempInxId = (HashMap)_indxIDRelAA.get(relName );
	   	HashMap tempIdInx = (HashMap)_idIndxRelAA.get(relName );
	   	
		DefaultComboBoxModel mod= new DefaultComboBoxModel();
		
		// there is a bug in JCombobox for v1.2.2
		//when there are more than 1 items whare the 
		//same name, it is not possible to select items
		// other than the first ocurrence
		int j= 2; 
		String last ="";
		String current;
		
		int i= 1; 	// if no relation instance select "None"
		mod.addElement("");
	    Iterator it = _dMM.getAInstanceAll().iterator();
	    
	    // check if there are items with same name
      	while ( it.hasNext()) {
      		temp = (ActionInstance)it.next();
      		current = temp.getName();
      		if (!(last.equals(current))){
      			mod.addElement(current);
      			j=2;
      		} else {
      			mod.addElement(current + " ("+  j++ + ")");
      		}
      		
      		last = current;
	      	tempInxId.put(Integer.toString(i),temp.getID() );
	      	tempIdInx.put(temp.getID(),Integer.toString(i++) );
      	}
      	tempCm.setModel(mod);
      	
		i= 0; 	// if no relation instance select "None"
		
      	if (ai != null)
      		i= Integer.parseInt((String)tempIdInx.get(ai.getID()));
      		
      	tempCm.setSelectedIndex(i);

	    	      
		return;  	
	}
/*
      String allActRle[] = _dMRelat.getAllActionRelations();
      int numberRel =allActRle.length; 
*/
	
	private void updateAARel(){
      String allAARle[] = _dMRelat.getAllActionActRelations();
      int numberAARel =allAARle.length; 

      String relName;
	//	TreeMap reActInstances = _aIns.getEntityRelations();    
		for (int j = 0; j < numberAARel; j++) {
			relName = allAARle[j];
			//get selected instance index
			JComboBox tempCm =(JComboBox)_RelCombos.get(relName);
			if (tempCm == null)
				continue;
			
			int indexSelect = tempCm.getSelectedIndex();
			
			if (indexSelect == 0){
				_aIns.setActionActRelation(relName,null);
				continue;

			}
			//get selected instance ID
			HashMap tempHM= (HashMap) _indxIDRelAA.get(relName);
			String tempID  = (String)	tempHM.get(Integer.toString(indexSelect));
			//System.out.println( "\n realtion : "+ relName+ " index =" +indexSelect
			//			+ " ID =" + tempID);

			ActionInstance tempEn = _dMM.getAInstance(tempID);
			
			//update the content of the relation related instsance
			if (tempEn != null)
				_aIns.setActionActRelation(relName,tempEn);
    	}
    }
    
	//16-1-2002
	//popup contextual type listener 
	MouseListener mosueListenerContext = new MouseAdapter(){
	    	public void mousePressed(MouseEvent e) {
	   		//enable right-mouse-button selection
	    		//int index = _actL.locationToIndex(e.getPoint());
	    		//_actL.setSelectedIndex(index);
			//selectAct(); 
			maybeShowPopup(e);
		}
		/*
	    	public void mouseEntered(MouseEvent e) {
	  		_popMenuContextType.show(e.getComponent(),
		        e.getX(), e.getY());
		}	
	    	public void mouseExited(MouseEvent e) {
	    		if (!(_popMenuContextType.getVisibleRect().
	    			contains(e.getX(), e.getY())));
	  			_popMenuContextType.setVisible(false);
		}	
	    	public void mouseClicked(MouseEvent e) {
		}
		*/
		public void mouseReleased(MouseEvent e) {
		  	maybeShowPopup(e);
		}
		
		public void maybeShowPopup(MouseEvent e) {
			//System.out.println( "\n button pressed");
			if (e.isPopupTrigger()) {
				//set current act-entity relation
				JComboBox comb = ((MetalComboBoxButton)e.getComponent()).getComboBox();
		      	//System.out.println( "\n selcted index: "+ comb.getSelectedIndex());
				if (comb.getSelectedIndex() <= 0) return;
				
		      	if (_combosRel.get(comb) != null)
					_currentActEntityRelation = (String)_combosRel.get(comb);
		      	//System.out.println( "\n relation: "+ _currentActEntityRelation);
		        	prepareContextmenu(_currentActEntityRelation);
				_popMenuContextType.show(e.getComponent(),
		        	e.getX(), e.getY());
		    	}
		}

	};
	
   //16-1-2002
   // add al contextual types defined in ContextualType class into the
   // JPopupMenu
   private void initContextTypeMenu(){
   	ContextualType contexType= ContextualType.getInstance();
   	String allTypes[] = contexType.getAllTypes();
   	for (int i = 0; i <allTypes.length; i++){
    		JCheckBoxMenuItem jcbm = new JCheckBoxMenuItem(allTypes[i]);
    		_bgroup.add(jcbm);
    		_popMenuContextType.add(jcbm);
    		jcbm.addActionListener(popupContext);
   	}
   	
   }
	
ActionListener popupContext = new ActionListener(){
	public void actionPerformed(ActionEvent e) {
		//System.out.println( "\n Action:right mouse clicked: "+
		//	e.getActionCommand());
			
	     	if (_aIns != null){
	     		if (_currentActEntityRelation!= null){
	     			_aIns.setEntityContextType(_currentActEntityRelation,
	     				e.getActionCommand());
	     		}
	      }
	     
	}
	
};

private void prepareContextmenu(String actEntityRel){
     	if (_aIns != null){
		TreeMap contextTypes=_aIns.getEContextTypes();
		JCheckBoxMenuItem jcbm;
		if (contextTypes.get(actEntityRel) != null){
			String contextType = (String)contextTypes.get(actEntityRel);
			int count=_popMenuContextType.getComponentCount();
			for (int i = 0; i <count; i++){
		    		jcbm= (JCheckBoxMenuItem)_popMenuContextType.getComponent(i);
		    		String type = jcbm.getActionCommand();
		    		if (contextType.equals(type)){
		    			jcbm.setState(true);
		    			return;
		    		}
		    		//System.out.println("item name: "+jcbm.getActionCommand());
   			}
   			
		}
     	}
	
}

//25-6-2002
//get selected AI
public ActionInstance getSelectedAI(){
	return _aIns; 
}//get selected action instance
   
}