/*
   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.event.*;
import java.util.*;
import java.io.*;
import domainModel.*;
import taskModellingTool.*;


public class EntityPane extends JPanel {
	
  	private DmManager _dMM=Manager.getXDM().getDmManager();	// default _dMM 
 	private static DmRelation _dMRelat = DmRelation.getInstance();
	private EntityInstance _eIns;
	private DmEdit _owner; 		//owner of this Jpanel
	private boolean _modified= false; 		//for monitoring user modification
	private boolean _conChanged= false; 		//for monitoring concept change

	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 _cardinality =new JLabel( "Cardinality");
	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 static final JLabel _label = new JLabel("Label");
	private static final JLabel _determinator = new JLabel("Determiner");
	
	private JPanel _userPanel, _systemPanel, _thingPanel,
		_relnsPanel,_insPanel, _interfacePanel, 
			_fieldPanel, _inLabelPanel, _inEmptyPanel,
			_inDeterPanel;
	private JLabel 	_mainLabel = new JLabel("Entity Instance");
	
	private JList _userL, _systemL, _thingL, _interfaceL;
	
	// put all entity concepts(including User and System types in _concepts
    private JComboBox _conCm = new JComboBox();
  	private JComboBox _cardCm = new JComboBox();

   	private JTabbedPane _tabPane;
  	private HashMap _conIndxID= new HashMap(); 	//   HashMap for pairs of concept
  												//and Index-ID 
	
  	private HashMap _listModel= new HashMap(); 	//   HashMap for pairs of list and DefaultListModel 
  	private HashMap _listIndxID= new HashMap(); 	//   HashMap for pairs of list and Index-ID 

  	private HashMap _indxIDRel; 	//  nested HashMap for pairs of index and ID 
  											//for relation instance
  	private HashMap _idIndxRel; 	//  nested HashMap for pairs of index and 
  											//ID for relation instance
  	private HashMap _RelCombos=new HashMap();
									 	//   HashMap for pairs of relation-name
  											// and comboBox
 	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 JTextField _labelT = new JTextField();
	
	//17-10-2001
	private JTextField _deterT = 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 _userIn = new JMenuItem("Add New User Instance");
  	private JMenuItem _systemIn = new JMenuItem("Add New System Instance");
  	private JMenuItem _thingIn = new JMenuItem("Add New Objcet Instance");
   	private JMenuItem _interfaceIn = new JMenuItem("Add New Interface Instance");
 
  	private JMenuItem _updateIn = new JMenuItem("Update");
  	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");
  
	public EntityPane(DmEdit owner){
		super();
        //_popMenu.add(_popNew);    
		_owner = owner;
		
		//17-10-2001
		//intiInterfaceLabel();
		intiEmptyPanel();
		intiObjEntityDeterminator();
		
        addMenuItemListener();	
		addModifyListener();
		add(getRootPanel());
		setTextColor(DmManager.getEnColor());
		
	}
	
	private void addMenuItemListener(){
	   _thingIn.addActionListener(new java.awt.event.ActionListener() {
	      	public void actionPerformed(ActionEvent e) {
	        	_dMM.newEIns();
				updateTab();
		//25-6-2002
		//update action-entity relations in action pane
		updateAErelations();

	      	}
	    });
    
	   _systemIn.addActionListener(new java.awt.event.ActionListener() {
		    public void actionPerformed(ActionEvent e) {
		        _dMM.newSIns();
					updateTab();
		//25-6-2002
		//update action-entity relations in action pane
		updateAErelations();

		    }
	    });
    
	   _userIn.addActionListener(new java.awt.event.ActionListener() {
	      	public void actionPerformed(ActionEvent e) {
	        	_dMM.newUIns();
	        	updateTab();
	      //25-6-2002
		//update action-entity relations in action pane
		updateAErelations();


	      	}
	    });
    
	   _interfaceIn.addActionListener(new java.awt.event.ActionListener() {
	      	public void actionPerformed(ActionEvent e) {
	        	_dMM.newIIns();
	        	updateTab();
		//25-6-2002
		//update action-entity relations in action pane
		updateAErelations();
	      	}
	    });
    
	   _updateIn.addActionListener(new java.awt.event.ActionListener() {
	      	public void actionPerformed(ActionEvent e) {
	      		storeChange();
	      	}
	    });
    
	   _deleteIn.addActionListener(new java.awt.event.ActionListener() {
	      	public void actionPerformed(ActionEvent e) {
				deleteIns();	      
	      	}
	    });
    
	   _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) {
				filter();
	      	}
	    });

		_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);

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

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

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

      		}
		});
    	
    	_conCm.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
      			setModified(true);
      			setConceptChanged(true);
			}
		});
    	
    	_cardCm.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
      			setModified(true);
			}
		});

   }
    
    private void setModified(boolean bo){
    	_modified = bo;
    	return;
    }
    
    private void setConceptChanged(boolean bo){
    	_conChanged = bo;
    	return;
    }
    
	
	private void filter(){
		if (_tabPane.getSelectedComponent().equals(_thingPanel))
			_owner.insTFilter(_eIns);
		else if (_tabPane.getSelectedComponent().equals(_systemPanel))
			_owner.insSFilter(_eIns);
		else if (_tabPane.getSelectedComponent().equals(_interfacePanel))
			_owner.insIFilter(_eIns);
		else
			_owner.insUFilter(_eIns);
		
	}
	
	private void deleteIns(){
		_dMM.removeEInstance(_eIns); 
		
		//update list
		updateTab();
	}
	
	private void updateTab(){
		if (_tabPane.getSelectedComponent().equals(_thingPanel)){
			setJlistContent(_thingL, 
				_dMM.getEiSome(ConceptType.getDefaultEntityType(),
				_dMM.getEInstanceAll()));
		}else if (_tabPane.getSelectedComponent().equals(_systemPanel)){
			setJlistContent(_systemL,  
				_dMM.getEiSome(ConceptType.getDefaultSystemType()));
		}else if (_tabPane.getSelectedComponent().equals(_interfacePanel)){
			setJlistContent(_interfaceL,  
				_dMM.getEiSome(ConceptType.getInterfaceType()));
		}else{
			setJlistContent(_userL,  
				_dMM.getEiSome(ConceptType.getDefaultUserType()));			
		}
	}
	
	private void editIns(){
		if (_eIns != null){
			EInstanceEdit id = new EInstanceEdit(MainFrame.getMainFrame(),
				"Edit Entity Instance",_eIns);
		}
	}
	
	private void resetTabs(){
		setJlistContent(_thingL, _dMM.getObjectIns());
			//_dMM.getEiSome(ConceptType.getDefaultEntityType(),
			//	_dMM.getEInstanceAll()));
			//_dMM.getEiSome(ConceptType.getDefaultEntityType()));
		_dMM.printEInstance(_dMM.getEInstanceAll());
		
		setJlistContent(_systemL,  
			_dMM.getEiSome(ConceptType.getDefaultSystemType()));
		setJlistContent(_userL,  
			_dMM.getEiSome(ConceptType.getDefaultUserType()));
		setJlistContent(_interfaceL,  _dMM.getInterfaceIns());
			//_dMM.getEiSome(ConceptType.getInterfaceType()));
			
		return;
		
	}
	
	public void resetThingList(Collection col){
		setJlistContent(_thingL, col);
	}
	
	public void resetSystemList(Collection col){
		setJlistContent(_systemL, col);
	}
	
	
	public void resetUserList(Collection col){
		setJlistContent(_userL, col);
	}
	
	public void resetInterfaceList(Collection col){
		setJlistContent(_interfaceL, col);
	}
	
	private JPanel getRootPanel(){
		JPanel rootPanel= new JPanel();
		//Dimension PanelD= new Dimension(200,100);
		
       	rootPanel.setLayout(new BorderLayout());
		rootPanel.add(_mainLabel,BorderLayout.NORTH);
     	rootPanel.add(getTabPanel(),BorderLayout.CENTER);
    	rootPanel.add(getInsPanel(),BorderLayout.SOUTH);
      	rootPanel.setPreferredSize(rootPanel.getPreferredSize());
		return rootPanel;	
	}
	
	private JTabbedPane getTabPanel(){
		_tabPane= new JTabbedPane();
		// Add the different tabs 
		_tabPane.addTab(DmConcept.getDefaultEntityConcept().getName(),
			null, getEntityTab());
		_tabPane.addTab(EntityInstance.getDefaultSystemInstance().getName(),
			null, 	getSystemTab());
		_tabPane.addTab(EntityInstance.getDefaultUserInstance().getName(),
			null, getUserTab());
		_tabPane.addTab(DmConcept.getInterfaceConcept().getName(),
			null, getInterfaceTab());
	//	_tabPane.setSize(_tabPane.getMaximumSize());
		
		//add listener
		_tabPane.addChangeListener(tabListener);
		
     	return _tabPane;	
      
	}
	
	ChangeListener tabListener = new ChangeListener(){
		public void stateChanged(ChangeEvent e) {
			JPanel jp = (JPanel)_tabPane.getSelectedComponent();
			
			// save change, if any
			storeChange();
			
			//add or remove interface label panel
			//17-10-2001
		//	validateInterfaceLabel(jp);

			//18-10-2001
			validateObjEntityDeterminator(jp);
			
			if (jp.equals(_userPanel)){
				selectUser();
			}else if (jp.equals(_systemPanel)){
				selectSystem();
			}else if (jp.equals(_interfacePanel)){
				selectInterface();
			}else{
				selectThing();
			}
			
        	setModified(false); 
        	return;
		}
	};
	
	private JPanel getUserTab(){
		_userPanel= new JPanel();
		_userL = new JList();
		
		_listIndxID.put(_userL, new HashMap());
			
		setJlistContent(_userL, 
			_dMM.getEiSome(ConceptType.getDefaultUserType(),
				_dMM.getEInstanceAll()));
		
		JScrollPane scrollP= new JScrollPane(_userL);
     	scrollP.setHorizontalScrollBarPolicy(
          JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);	//	_NEVER);
     	scrollP.setVerticalScrollBarPolicy(
          JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
			
		_userPanel.add(scrollP);
		_userL.setVisibleRowCount(NUMBER_OF_ROWS);
		_userL.setFixedCellWidth(CELL_WIDTH);

		_userL.addListSelectionListener(userListener);
		
		_userL.addMouseListener(popupListener);		
		_userPanel.addMouseListener(popupListener);
		return _userPanel;	
	}
	
	ListSelectionListener userListener = new ListSelectionListener(){
		public void valueChanged(ListSelectionEvent e) {
			storeChange();
			selectUser();
        	setModified(false); 
        	return;
		}
	};
	
	private JPanel getInterfaceTab(){
		_interfacePanel= new JPanel();
		_interfaceL = new JList();
		
		_listIndxID.put(_interfaceL, new HashMap());
			
		setJlistContent(_interfaceL, 
			_dMM.getInterfaceIns());
			//getEiSome(ConceptType.getInterfaceType(),
			//	_dMM.getEInstanceAll()));
		
		JScrollPane scrollP= new JScrollPane(_interfaceL);
     	scrollP.setHorizontalScrollBarPolicy(
          JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);	//	_NEVER);
     	scrollP.setVerticalScrollBarPolicy(
          JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
			
		_interfacePanel.add(scrollP);
		_interfaceL.setVisibleRowCount(NUMBER_OF_ROWS);
		_interfaceL.setFixedCellWidth(CELL_WIDTH);

		_interfaceL.addListSelectionListener(interfaceListener);
		
		_interfaceL.addMouseListener(popupListener);		
		_interfacePanel.addMouseListener(popupListener);
		return _interfacePanel;	
	}
	
	ListSelectionListener interfaceListener = new ListSelectionListener(){
		public void valueChanged(ListSelectionEvent e) {
			storeChange();
			selectInterface();
        	setModified(false); 
        	return;
		}
	};
	
	MouseListener popupListener = new MouseAdapter(){
    	public void mousePressed(MouseEvent e) {
			storeChange();
	 		//enable right-mouse-button selection
    		JList jl= getList();
			int index = jl.locationToIndex(e.getPoint());
			jl.setSelectedIndex(index);
			
			if (jl.equals(_thingL))
				selectThing();
			else if (jl.equals(_userL))
				selectUser();
			else if (jl.equals(_interfaceL))
				selectInterface();
			else
				selectSystem();
			
			maybeShowPopup(e);
		}	
    	public void mouseClicked(MouseEvent e) {
			//if click more than once, invoke filter
			if (e.getClickCount() > 1){
				JList jl= getList();
				if (jl.equals(_thingL))
					_owner.insTFilter(_eIns);
				else if (jl.equals(_userL))
					_owner.insUFilter(_eIns);
				else if (jl.equals(_interfaceL))
					_owner.insIFilter(_eIns);
				else
					_owner.insSFilter(_eIns);
			}
		}	


		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 JList getList(){
		JPanel jp = (JPanel)_tabPane.getSelectedComponent();
		if (jp.equals(_userPanel)){
			return _userL;
		}else if (jp.equals(_systemPanel)){
			return _systemL;
		}else if (jp.equals(_interfacePanel)){
			return _interfaceL;
		}else{
			return _thingL;
		}
		
	}
	
	private void constructMenu(){
		if (_tabPane.getSelectedComponent().equals(_thingPanel)){
			_popMenu.removeAll();    
			_popMenu.add(_thingIn);
			addCommonMenuItem();
		}else if (_tabPane.getSelectedComponent().equals(_systemPanel)){
			_popMenu.removeAll();    
			_popMenu.add(_systemIn);    
			addCommonMenuItem();
		}else if (_tabPane.getSelectedComponent().equals(_interfacePanel)){
			_popMenu.removeAll();    
			_popMenu.add(_interfaceIn);    
			addCommonMenuItem();
		}else{
			_popMenu.removeAll();    
			_popMenu.add(_userIn);    
			addCommonMenuItem();
		}
		return;	
	}
	private void addCommonMenuItem(){
		if (_eIns == 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()); 
	        if (_modified)
				_popMenu.add(_updateIn);
			_popMenu.add(_deleteIn);    
			_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 selectUser(){
		//String eiName = (String)_userL.getSelectedValue();
		//updateIns(eiName,ConceptType.getDefaultUserType());
		
		int i = _userL.getSelectedIndex();
		HashMap indexId = (HashMap)_listIndxID.get(_userL);
		String iD = (String)indexId.get(Integer.toString(i));
		updateIns(iD,ConceptType.getDefaultUserType());
	}
	
	private void selectSystem(){
		//String eiName = (String)_systemL.getSelectedValue();
		//updateIns(eiName,ConceptType.getDefaultSystemType());
		int i = _systemL.getSelectedIndex();
		HashMap indexId = (HashMap)_listIndxID.get(_systemL);
		String iD = (String)indexId.get(Integer.toString(i));
		updateIns(iD,ConceptType.getDefaultSystemType());
		
	}
	
	
	private void selectThing(){
		//String eiName = (String)_thingL.getSelectedValue();
		//updateIns(eiName,ConceptType.getDefaultEntityType());
		
		int i = _thingL.getSelectedIndex();
		HashMap indexId = (HashMap)_listIndxID.get(_thingL);
		String iD = (String)indexId.get(Integer.toString(i));
		updateIns(iD,ConceptType.getDefaultEntityType());
		
	}

	private void selectInterface(){
		
		int i = _interfaceL.getSelectedIndex();
		HashMap indexId = (HashMap)_listIndxID.get(_interfaceL);
		String iD = (String)indexId.get(Integer.toString(i));
		updateIns(iD,ConceptType.getInterfaceType());
	}
	
	public void updateIns(String eiId, String type){
		if (eiId == null){
			setFieldsContent(null, type);
			setRelationContent(null);
			_eIns = null;
		} else {
			EntityInstance ei = _dMM.getEInstance(eiId);
			_eIns = ei;
			setFieldsContent(ei, ei.getConceptOf().getType());
			setRelationContent(ei);
		}
		//refresh();
	}

/*	public void updateIns(String eiName, String type){
		if (eiName == null){
			setFieldsContent(null, type);
			setRelationContent(null);
			_eIns = null;
		} else {
			EntityInstance ei = _dMM.getEi(eiName, type);
			_eIns = ei;
			setFieldsContent(ei, type);
			setRelationContent(ei);
		}
		//refresh();
	}
*/
	private JPanel getSystemTab(){
		_systemPanel= new JPanel();
		_systemL = new JList();
		
		_listIndxID.put(_systemL, new HashMap());

	//	setJlistContent(_systemL,  
	//		_dMM.getEiSome(ConceptType.getDefaultSystemType()));
		setJlistContent(_systemL, 
			_dMM.getEiSome(ConceptType.getDefaultSystemType(),
				_dMM.getEInstanceAll()));
			
		JScrollPane scrollP= new JScrollPane(_systemL);
     	scrollP.setHorizontalScrollBarPolicy(
          JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);	//	_NEVER);
     	scrollP.setVerticalScrollBarPolicy(
          JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
                   
		_systemPanel.add(scrollP);
		_systemL.setVisibleRowCount(NUMBER_OF_ROWS);
		_systemL.setFixedCellWidth(CELL_WIDTH);
		_systemL.addListSelectionListener(systemListener);
		
		_systemL.addMouseListener(popupListener);		
		_systemPanel.addMouseListener(popupListener);
		return _systemPanel;	
	}

	
	ListSelectionListener systemListener = new ListSelectionListener(){
		public void valueChanged(ListSelectionEvent e) {
			storeChange();
			selectSystem();
        	setModified(false); 
        	return;
		}
	};
	
	private JPanel getEntityTab(){
		_thingPanel= new JPanel();
		_thingL = new JList();
		
		_listIndxID.put(_thingL, new HashMap());

		setJlistContent(_thingL, _dMM.getObjectIns());
			//_dMM.getEiSome(ConceptType.getDefaultEntityType(),
			//	_dMM.getEInstanceAll()));
					
		JScrollPane scrollP= new JScrollPane(_thingL);
     	scrollP.setHorizontalScrollBarPolicy(
          JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);	//	_NEVER);
     	scrollP.setVerticalScrollBarPolicy(
          JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
          
		_thingPanel.add(scrollP);
		//	_thingL.setSize(_thingL.getMaximumSize());
		_thingL.setVisibleRowCount(NUMBER_OF_ROWS);
		_thingL.setFixedCellWidth(CELL_WIDTH);

		_thingL.addListSelectionListener(thingListener);
		
		_thingL.addMouseListener(popupListener);		
		_thingPanel.addMouseListener(popupListener);

		return _thingPanel;	
	}
	
	ListSelectionListener thingListener = new ListSelectionListener(){
		public void valueChanged(ListSelectionEvent e) {
			storeChange();
			selectThing();
        	setModified(false); 
        	return;
		}
	};
	
	/** remove all content for list if there is any,
	* then populate list with user
	*/
	public void setJlistContent(JList list, Collection user ){
		list.removeAll(); 
		Iterator it = user.iterator();
		EntityInstance ei;
		DefaultListModel model = new DefaultListModel();
		_listModel.put(list, model);

		HashMap indexID = (HashMap)_listIndxID.get(list);
		indexID.clear();
		int i =0;
		
		// 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;
		
		while (it.hasNext()){
			ei = (EntityInstance)it.next();
			
      		current = ei.getName();
      		if (!(last.equals(current))){
      			model.addElement(current);
      			j=2;
      		} else {
      			model.addElement(current + " ("+  j++ + ")");
      		}
      		
      		last = current;

      		//model.addElement(ei.getName());
			indexID.put(Integer.toString(i++),ei.getID() );
		}
		list.setModel(model);
		return;	
	}

	private JPanel getInsPanel(){
		_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(){
		if (_fieldPanel != null) return _fieldPanel;
			
		_fieldPanel= new JPanel();
      	_fieldPanel.setLayout(new BorderLayout());
      	
		JPanel fieldsPanel= new JPanel();
		
      	fieldsPanel.setLayout(new GridLayout(7,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(_cardinality);
      //	_cardCm = new JComboBox();
      	fieldsPanel.add(_cardCm);
      	fieldsPanel.add(_prem);
      	fieldsPanel.add(_premT);
      	fieldsPanel.add(_postm);
     //	_postmT = new JTextField(); 	//_eIns.getPostModifier());
      	fieldsPanel.add(_postmT);
		
      	fieldsPanel.add(_label);
      	fieldsPanel.add(_labelT);
		
      //	fieldsPanel.add(_inDeterPanel);
      //	fieldsPanel.add(_deterT);
		
		_fieldPanel.add(fieldsPanel,BorderLayout.NORTH);
	//17-10-2001	
		_fieldPanel.add(_inDeterPanel, BorderLayout.SOUTH);

		
     	return _fieldPanel;	
		
	}
	
	public void setFieldsContent(EntityInstance ei, String type){
		_conIndxID.clear();
		
		if (ei == null)
			clearFieldsContent();
		else{
			//clearFieldsContent();
			_nameT.setText(ei.getName());
			
			DefaultComboBoxModel mod1= new DefaultComboBoxModel();
			int i = 0;
			Iterator it;
			
			//2001-8-16
			if (ConceptType.isObjectType(type)){
				it = _dMM.getObjectCons().iterator();
				
			}else {
				it = _dMM.getConceptSome(type).iterator();
			}
				
			DmConcept con;
	      	while ( it.hasNext()) {
	      		con=(DmConcept)it.next();
	      		mod1.addElement(con.getName()+ "-" + con.getType());
				
				_conIndxID.put(Integer.toString(i++),con.getID());
	      	}
      		_conCm.setModel(mod1);
      		
			//System.out.println( "entity concept name=" +ei.getConceptOf().getName()+
			//	"-" + ei.getConceptOf().getType()+ ei.getConceptOf().getID());

			_conCm.setSelectedItem(ei.getConceptOf().getName()+
				"-" + type);
			
			DefaultComboBoxModel mod= new DefaultComboBoxModel(
					EntityInstance.getCardinalityAll());
      		_cardCm.setModel(mod);
   			_cardCm.setSelectedItem(ei.getCardinality());
			
   			String pre = ei.getPreModifier();
   			if (pre == null || pre.equals(""))
				_premT.setText("");
			else 
				_premT.setText(pre);
			
   			String post = ei.getPostModifier();
   			if (post == null || post.equals(""))
				_postmT.setText("");
			else 
				_postmT.setText(post);
				
 			String note = ei.getNote();
   			if (note == null || note.equals(""))
				_noteA.setText("");
			else 
				_noteA.setText(note);
		//17-10-2001		
			String label = ei.getLabel();
   			if (label == null || label.equals(""))
				_labelT.setText("");
			else 
				_labelT.setText(label);
				
			String deter = ei.getDeterminator();
   			if (deter == null || deter.equals(""))
				_deterT.setText("");
			else 
				_deterT.setText(deter);
		/*	//if is is an interface instance
			if (ei instanceof InterfaceInstance){
				
   				//String label = ((InterfaceInstance)ei).getLabel();
				//System.out.println("upto here 8");

			}
		*/	
		}
		
		setModified(false);
		setConceptChanged(false);
		
	}
	
	
	private void clearFieldsContent(){
		_nameT.setText("");
		DefaultComboBoxModel mod= new DefaultComboBoxModel();
		_conCm.setModel(mod);
		_cardCm.setModel(mod);
		_premT.setText("");
		_postmT.setText("");
		_labelT.setText("");
		_deterT.setText("");

		_noteA.setText("");
	}
	
	private JPanel getNotePanel(){
		JPanel notePanel= new JPanel();
		
		Dimension notePanelD= new Dimension(200,158);	//179);
      	notePanel.setPreferredSize(notePanelD);
      
      	notePanel.setLayout(new BorderLayout());
							//new GridLayout(2,1));
		
    	notePanel.add(_note,BorderLayout.NORTH);
     	_noteA.setLineWrap(true);
		//_noteA.setFont(new Font("Dialog", Font.PLAIN, 12));
		//_noteA.getAccessibleContext().setAccessibleName("Editable text area");
     	
     	JScrollPane scrollP= new JScrollPane(_noteA);
     	scrollP.setHorizontalScrollBarPolicy(
          JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
     	scrollP.setVerticalScrollBarPolicy(
          JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        //scrollP.getViewport().add(_noteA);    
 		
      	notePanel.add(scrollP, BorderLayout.CENTER);
     	
      	//notePanel.add(_noteA, BorderLayout.CENTER);
      	
     	return notePanel;	
      
	}
	
	
	private JPanel getRelationPanel(){
		_relnsPanel= new JPanel();
   		_indxIDRel = new HashMap();
   		_idIndxRel = new HashMap(); 
		
		
      	String allEnRle[] = _dMRelat.getAllEntityRelations();
      	int numberRel =allEnRle.length; 
      	_relnsPanel.setLayout(new GridLayout(numberRel+1,2));
      	String relName;
      	
      	//add a empty row
		_relnsPanel.add(new JLabel());
		_relnsPanel.add(new JLabel(" "));
		
		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);
			_relnsPanel.add(getEInsCm(relName));
		}
    	
    	return _relnsPanel;
      
	}
	
	public void setRelationContent(EntityInstance ei){
		_indxIDRel = new HashMap();
   		_idIndxRel = new HashMap(); 
      	String allEnRle[] = _dMRelat.getAllEntityRelations();
      	int numberRel =allEnRle.length;
	    String relName;
	    
		if (ei == null){
			for (int j = 0; j < numberRel; j++) {
				relName = allEnRle[j];
				clearEiRelInsContent(relName);
	    	}
		}
		else{

			TreeMap reEnInstances = ei.getEntityRelations();    
			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));
				
	    	}
		}
	}
	
	private JPanel getRelPanel(){
		JPanel _relnsPanel= new JPanel();
    	return _relnsPanel;
      
	}
	
	private JComboBox getEInsCm(String relName ){
    	JComboBox tempCm = new JComboBox();
    	
    	tempCm.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
      			setModified(true);
			}
		});

	    _RelCombos.put(relName,tempCm);
		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();
      	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;
      		
      		//mod.addElement(temp.getName());
	      	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;  	
	}
	
	
/*
			int indexSelect = tempCm.getSelectedIndex();
			
			if (indexSelect == 0){
				_eIns.setEntityRelation(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);

*/
	public void updateChange(){
		storeChange();
	}

	private void storeChange(){
		// update Enttity instance attributes
		if (_eIns == null || !(_modified)) {	
			return;
		}
		
     	_eIns.setName(_nameT.getText());
     	
     	if (_conChanged){
			//System.out.println( "******concept selection changed : ");
	     	String ConceptName= (String)_conCm.getSelectedItem();
			int indexSelect = _conCm.getSelectedIndex();
			String tempID  = (String)	_conIndxID.get(Integer.toString(indexSelect));
			DmConcept tempCon = _dMM.getConcept(tempID);
	     	//DmConcept temp =_dMM.getEConceptAny(ConceptName);
	     	if (tempCon == null)
	     		System.out.println("did not find concept: "+ ConceptName);
	     	else
	     		_eIns.setConceptOf(tempCon);
     	}
     	
     //	_eIns.setDirty(_dirtyC.isSelected()); 
     	String cardi= (String)_cardCm.getSelectedItem();
     	_eIns.setCardinality(cardi);
     	_eIns.setPreModifier(_premT.getText());
     	_eIns.setPostModifier(_postmT.getText());
        
        _eIns.setLabel(_labelT.getText());
        _eIns.setDeterminator(_deterT.getText());
     	_eIns.setNote(_noteA.getText());
        updateRel();
		//if is is an interface instance

       /* if (_eIns instanceof InterfaceInstance){
     		((InterfaceInstance)_eIns).setLabel(_labelT.getText());

		}
		*/	
      //2001-2-14
      // mark related task dirty
      DmManager.getInstance().markTaskDirty(_eIns);
      _modified = false;
      _conChanged = false;

	}
	
	
	private void updateRel(){
      String allActRle[] = _dMRelat.getAllEntityRelations();
      int numberRel =allActRle.length; 
      String relName;
	//	TreeMap reActInstances = _eIns.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){
				_eIns.setEntityRelation(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){
				_eIns.setEntityRelation(relName,tempEn);
			}
    	}
    }
    
    
    public void setTextColor(Color co){
    	DmManager.setEnColor(co);
    	setMenuItemColor( co);	
      	setLabelColor(co);
      	setEnRelCol(co);
      	
    	_tabPane.setForeground(co);
 		_thingL.setForeground(co);    
 		_systemL.setForeground(co);    
 		_userL.setForeground(co); 
 		_interfaceL.setForeground(co);    

 	
 		//textfields
		_nameT.setForeground(co);    
		_conCm.setForeground(co);    
		_cardCm.setForeground(co);    
		_premT.setForeground(co);    
		_postmT.setForeground(co);
		_labelT.setForeground(co);
		_deterT.setForeground(co);
		_noteA.setForeground(co);    

		return;
    	
    }
     
    public void setEnRelCol(Color co){
		
      	String allActRle[] = _dMRelat.getAllEntityRelations();
      	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);

		}	
		
		return;
    }
   
    public void setLabelColor(Color co){
    	//labels
    	_mainLabel.setForeground(co);
		_name.setForeground(co);    
		_concept.setForeground(co);    
		_cardinality.setForeground(co);    
		_prem.setForeground(co);    
		_postm.setForeground(co);
		_label.setForeground(co);
		_determinator.setForeground(co);

		_note.setForeground(co);
		return;
    }
    public void setMenuItemColor(Color co){

		//popup meniItems
		_userIn.setForeground(co);    
		_systemIn.setForeground(co);    
		_thingIn.setForeground(co);
		_interfaceIn.setForeground(co);
		_updateIn.setForeground(co);    
		_deleteIn.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 Entity Instance", DmManager.getEnColor());    
		if (color == null)
   			return;
   			
    	setTextColor(color);
   		return;
   	
    }
    
    public void setColorDefault(){
    	setTextColor(DmManager.ENTITY_COLOR);
   	
    }
    
    private void updateName(String name){
    	JList jl= getList();
		int i = jl.getSelectedIndex();
		
		((DefaultListModel)_listModel.get(jl)).set(i, name);
   	
    }
	
	private void intiInterfaceLabel(){
		if (_inLabelPanel == null){
			_inLabelPanel= new JPanel();

			_inLabelPanel.setLayout(new GridLayout(1,2));
	
	      	_inLabelPanel.add(_label );
	    	_inLabelPanel.add(_labelT );
		} 
		
		if (_inEmptyPanel == null){
			_inEmptyPanel= new JPanel();

			_inEmptyPanel.setLayout(new GridLayout(1,2));
	
	      	_inEmptyPanel.add(new JLabel() );
	      	JTextField tf = new JTextField();
	      	tf.setVisible(false);
	    	_inEmptyPanel.add(tf);
		} 
		
		return;
	}
		
	private void validateInterfaceLabel(JPanel jp){
		Component com = _fieldPanel.getComponent(_fieldPanel.
			getComponentCount()-1);
		if (jp.equals(_interfacePanel)){
			if (!(com.equals(_inLabelPanel)) && 
				!(com.equals(_inEmptyPanel))){
					_fieldPanel.add(_inLabelPanel, BorderLayout.SOUTH);
					
			}else if (com.equals(_inEmptyPanel)){
					_fieldPanel.remove(_inEmptyPanel);
					_fieldPanel.add(_inLabelPanel, BorderLayout.SOUTH);
			}
				
		} else {
			if (!(com.equals(_inLabelPanel)) && 
				!(com.equals(_inEmptyPanel))){
					_fieldPanel.add(_inEmptyPanel, BorderLayout.SOUTH);
					
			}else if (com.equals(_inLabelPanel)){
					_fieldPanel.remove(_inLabelPanel);
					_fieldPanel.add(_inEmptyPanel, BorderLayout.SOUTH);
			}
		}
		
		_fieldPanel.paintImmediately(_fieldPanel.getBounds());
		
		return;
	}
	//17-10-2001
	private void intiEmptyPanel(){
		
		if (_inEmptyPanel == null){
			_inEmptyPanel= new JPanel();

			_inEmptyPanel.setLayout(new GridLayout(1,2));
	
	      	_inEmptyPanel.add(new JLabel() );
	      	JTextField tf = new JTextField();
	      	tf.setVisible(false);
	    	_inEmptyPanel.add(tf);
		} 
		
		return;
	}

//18-10-2001
	
	private void intiObjEntityDeterminator(){
		if (_inDeterPanel == null){
			_inDeterPanel= new JPanel();

			_inDeterPanel.setLayout(new GridLayout(1,2));
	
	      	_inDeterPanel.add(_determinator );
	    	_inDeterPanel.add(_deterT );
		} 
		
		return;
	}
		
	private void validateObjEntityDeterminator(JPanel jp){
		Component com = _fieldPanel.getComponent(_fieldPanel.
			getComponentCount()-1);
		if (!(jp.equals(_interfacePanel))){
			if (!(com.equals(_inDeterPanel)) && 
				!(com.equals(_inEmptyPanel))){
					_fieldPanel.add(_inDeterPanel, BorderLayout.SOUTH);
					
			}else if (com.equals(_inEmptyPanel)){
					_fieldPanel.remove(_inEmptyPanel);
					_fieldPanel.add(_inDeterPanel, BorderLayout.SOUTH);
			}
				
		} else {
			if (!(com.equals(_inDeterPanel)) && 
				!(com.equals(_inEmptyPanel))){
					_fieldPanel.add(_inEmptyPanel, BorderLayout.SOUTH);
					
			}else if (com.equals(_inDeterPanel)){
					_fieldPanel.remove(_inDeterPanel);
					_fieldPanel.add(_inEmptyPanel, BorderLayout.SOUTH);
			}
		}
		
		_fieldPanel.paintImmediately(_fieldPanel.getBounds());
		
		return;
	}
//25-6-2002
//update action-entity relations in action pane
private void updateAErelations(){
	String aiName = "";
	if (_owner != null)
		if (_owner.getActPane() != null){
			if ((_owner.getActPane()).getSelectedAI() != null){	
				ActionInstance aiTemp = (_owner.getActPane()).getSelectedAI();
				(_owner.getActPane()).updateIns(aiTemp.getName());
			}else
				(_owner.getActPane()).updateIns(aiName);
		}
		return;
}

}