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


public class EInstanceEdit {
	private EntityInstance _eIns;
	
  	////Shijian 2001-1-23
  	private XManager _xManager = FileManager.getXDM();     // grab the xmanager
  	private DmManager _dMM=_xManager.getDmManager();	// default _dMM 
  	private static DmRelation _dMRelat = DmRelation.getInstance();
 	private HashMap _indxID; 	//  pairs of index and ID for concepts
 	private HashMap _idIndx; 	//  pairs of index and ID for concepts
  	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 String _title = "Edit Entity Instance";	//default dialog box title
	private JFrame  _parent = null; //default parent
	private JOptionPane  _pane ;
	private JDialog eConDialog;
	private	JPanel _englishCard;

	private boolean  _OkButtonPressed= false;
	private boolean  _CancelButtonPressed= false;

	//define labels to be used in the dialod box
	private static final String _name = "Name";
	private static final String _concept = "Concept";
	private static final String _dirty = "Dirty";
	private static final String _cardinality = "Cardinality";
	private static final String _prem = "Premodifier";
	private static final String _postm = "Postmodifier";
	private static final String _plural = "Plural";
	private static final String _note = "Comment";
	
	// put all entity concepts(including User and System types in _concepts
   private JComboBox _conCm, _cardCm;
 
   //define editable components
	private JTextField _nameT,_premT,_postmT, _pluralT;

   private JCheckBox _dirtyC,_pluralC;
   private JTextArea _noteA;
   
	public EInstanceEdit(EntityInstance eCon,DmManager dmm ){
		super();
		_eIns = eCon;
		_dMM =dmm;

		_pane = new JOptionPane(getAllPanels(),
    		JOptionPane.PLAIN_MESSAGE,JOptionPane.OK_CANCEL_OPTION);
    		
	   eConDialog = _pane.createDialog(_parent, _title);
		eConDialog.show();
		
		onButtonPress();
	}
	
	public EInstanceEdit(JFrame parent, String title, 
						 EntityInstance eCon){
		super();
		_eIns = eCon;
		_parent =parent;
		_title =title;
		
		_pane = new JOptionPane(getAllPanels(),
    		JOptionPane.PLAIN_MESSAGE,JOptionPane.OK_CANCEL_OPTION);
    		
	   eConDialog = _pane.createDialog(_parent, _title);
		eConDialog.show();
		
		onButtonPress();
				
	}

	private JComponent[] getAllPanels(){
		JComponent[] components = new JComponent[3];
		components[0] = getFieldsPanel();
		components[1] = getRelationPanel();
		components[2] = getNotePanel();
		return components;	
	}

	private JPanel getFieldsPanel(){
		JPanel fieldsPanel= new JPanel();
      fieldsPanel.setLayout(new GridLayout(6,2));
		
      fieldsPanel.add(new JLabel(_name));
     	_nameT = new JTextField(_eIns.getName());
      fieldsPanel.add(_nameT);
      
      //initialize concept Combon box
      fieldsPanel.add(new JLabel(_concept));
      _conCm = new JComboBox();
      Iterator i = _dMM.getEConceptAll().iterator();
      while ( i.hasNext()) {
      	_conCm.addItem(((DmConcept)i.next()).getName());
      }
	  	_conCm.setSelectedItem(_eIns.getConceptOf().getName());
	  fieldsPanel.add(_conCm);
	  
		fieldsPanel.add(new JLabel(_dirty));
    	_dirtyC = new JCheckBox("",_eIns.getDirty());
      fieldsPanel.add(_dirtyC);
		// 
      fieldsPanel.add(new JLabel(_cardinality));
      _cardCm = new JComboBox(EntityInstance.getCardinalityAll());
   	_cardCm.setSelectedItem(_eIns.getCardinality());
      fieldsPanel.add(_cardCm);
		
      fieldsPanel.add(new JLabel(_prem));
     	_premT = new JTextField(_eIns.getPreModifier());
      fieldsPanel.add(_premT);
		
      fieldsPanel.add(new JLabel(_postm));
     	_postmT = new JTextField(_eIns.getPostModifier());
      fieldsPanel.add(_postmT);
		
     	return fieldsPanel;	
		
	}
	
	private JPanel getNotePanel(){
		JPanel notePanel= new JPanel();
		Dimension notePanelD= new Dimension(400,100);
      notePanel.setPreferredSize(notePanelD);
      
      notePanel.setLayout(new BorderLayout());
							//new GridLayout(2,1));
		
      notePanel.add(new JLabel(_note),BorderLayout.NORTH);
     	_noteA = new JTextArea(_eIns.getNote());
     	_noteA.setRows(4);	//4 rows of text
      notePanel.add(_noteA, BorderLayout.CENTER);
     	return notePanel;	
      
	}
	
/*	
	private void updatePluralT(){
      if (_massC.isSelected()) {		//isMassNoun
      	_pluralT.setText("");
       	_pluralT.setEditable(false);
      } else _pluralT.setEditable(true);
      
      _pluralT.paintImmediately(_englishCard.getBounds());

  	}
*/
	private void onButtonPress(){
		
		Object selectedValue = _pane.getValue();
		if (selectedValue != null && selectedValue != JOptionPane.UNINITIALIZED_VALUE){
			Integer sv = (Integer)selectedValue;
			
			if( sv.intValue()  == JOptionPane.OK_OPTION) {
				//update _eIns	
				onOKBotton();
			}else onCancelB();
		}

	}
	
	private void onOKBotton(){
		_OkButtonPressed= true;
		_CancelButtonPressed= false;
		System.out.println( "\n Ok button pressed");
		
		// update Enttity instance attributes
     	_eIns.setName(_nameT.getText());
     	String ConceptName= (String)_conCm.getSelectedItem();
     	_eIns.setConceptOf(_dMM.getEConceptAny(ConceptName));
     	_eIns.setDirty(_dirtyC.isSelected());
     	String cardi= (String)_cardCm.getSelectedItem();
     	System.out.println( "\n Cardinality is: "+ "\"" + cardi+ "\"");
     	_eIns.setCardinality(cardi);
     	_eIns.setPreModifier(_premT.getText());
     	_eIns.setPostModifier(_postmT.getText());

     	_eIns.setNote(_noteA.getText());
        updateRel();
      //2001-2-14
      // mark related task dirty
      DmManager.getInstance().markTaskDirty(_eIns);
	}
	
	private void onCancelB(){
		_OkButtonPressed= false;
		_CancelButtonPressed= true;
		System.out.println( "\n Cancel button pressed");

	}
	
	public boolean isOKButton(){
		return _OkButtonPressed;
	}
	
	public boolean isCancelButton(){
		return _CancelButtonPressed;
	}
	
	public String getName(){
		return _eIns.getName();
	}
	
	private JPanel getRelationPanel(){
		JPanel relnsPanel= new JPanel();
   	_indxIDRel = new HashMap();
   	_idIndxRel = new HashMap();
		
		
      String allEnRle[] = _dMRelat.getAllEntityRelations();
      int numberRel =allEnRle.length; 
      relnsPanel.setLayout(new GridLayout(numberRel,2));
      String relName;
		TreeMap reEnInstances = _eIns.getEntityRelations();    
		for (int j = 0; j < numberRel; j++) {
			relName = allEnRle[j];
      		_indxIDRel.put(relName,new HashMap() );
      		_idIndxRel.put(relName,new HashMap() );;
			relnsPanel.add(new JLabel(relName));
			relnsPanel.add(getEInsCm(relName,
				(EntityInstance)reEnInstances.get(relName)));
			
    	}
    	
    	return relnsPanel;
      
	}
	
	private JComboBox getEInsCm(String relName,EntityInstance en ){
    	JComboBox tempCm = new JComboBox();
	    _RelCombos.put(relName,tempCm);
			//assume name is unique for User and system instances
	      
	    Iterator it = _dMM.getEInstanceAll().iterator();
	    EntityInstance temp ;
	   	HashMap tempInxId = (HashMap)_indxIDRel.get(relName );
	   	HashMap tempIdInx = (HashMap)_idIndxRel.get(relName );;
	      
	   	tempCm.addItem("");
	    int i =1;	// 0;	// for tracking JcomboBox index
	    while ( it.hasNext()) {
	      	temp = (EntityInstance)it.next();
	      	tempCm.addItem(temp.getName());
	      	tempInxId.put(Integer.toString(i),temp.getID() );
	      	tempIdInx.put(temp.getID(),Integer.toString(i++) );
	    }
	            	
	    i= 0; 	// if no relation instance select "None"
	    if (en != null) {
	    	i= Integer.parseInt((String)tempIdInx.get(en.getID()));
	      	
	    }
	      
		tempCm.setSelectedIndex(i);
		  	
		return tempCm;
	}
	
	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);
			}
    	}
    	
		
	}
	
	
	
}