/*
   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 AInstanceEdit {
	private ActionInstance _aIns;
	
  ////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 _aInsDialog;
	private	JPanel _relations;

	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 _prem = "Premodifier";
	private static final String _postm = "Postmodifier";
	private static final String _relat = "Relations";
	private static final String _note = "Comment";
	
	// put all entity concepts(including User and System types in _concepts
   private JComboBox _conCm, _cardCm, _enInsCm;
 
   //define editable components
	private JTextField _nameT,_premT,_postmT;

   private JCheckBox _dirtyC;
   private JTextArea _noteA;
   
	public AInstanceEdit(ActionInstance aIns,DmManager dmm ){
		super();
		_aIns = aIns;
		_dMM =dmm;

		_pane = new JOptionPane(getAllPanels(),
    		JOptionPane.PLAIN_MESSAGE,JOptionPane.OK_CANCEL_OPTION);
    		
	   _aInsDialog = _pane.createDialog(_parent, _title);
		_aInsDialog.show();
		
		onButtonPress();
	}
	
	public AInstanceEdit(JFrame parent, String title, 
						 ActionInstance aIns){
		super();
		_aIns = aIns;
		_parent =parent;
		_title =title;
		
		_pane = new JOptionPane(getAllPanels(),
    		JOptionPane.PLAIN_MESSAGE,JOptionPane.OK_CANCEL_OPTION);
    		
	   _aInsDialog = _pane.createDialog(_parent, _title);
		_aInsDialog.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(5,2));
		
      fieldsPanel.add(new JLabel(_name));
     	_nameT = new JTextField(_aIns.getName());
      fieldsPanel.add(_nameT);
      
      //initialize concept Combon box
      fieldsPanel.add(new JLabel(_concept));
		initialseConCm();
		fieldsPanel.add(_conCm);
	  
		fieldsPanel.add(new JLabel(_dirty));
    	_dirtyC = new JCheckBox("",_aIns.getDirty());
      fieldsPanel.add(_dirtyC);
		
      fieldsPanel.add(new JLabel(_prem));
     	_premT = new JTextField(_aIns.getPreModifier());
      fieldsPanel.add(_premT);
		
      fieldsPanel.add(new JLabel(_postm));
     	_postmT = new JTextField(_aIns.getPostModifier());
      fieldsPanel.add(_postmT);
		
     	return fieldsPanel;	
		
	}
	
	private void initialseConCm(){
      _conCm = new JComboBox();
   	_indxID = new HashMap();
   	_idIndx = new HashMap();
   	
      Iterator it = _dMM.getConceptSome(
      	ConceptType.getDefaultActionType()).iterator();
      int i = 0;	// for tracking JcomboBox index
      DmConcept temp ;
      while ( it.hasNext()) {
      	temp = (DmConcept)it.next();
      	_conCm.addItem(temp.getName());
      	_indxID.put(Integer.toString(i),temp.getID() );
      	_idIndx.put(temp.getID(),Integer.toString(i++) );
      }
      
      String idSt	=(String)_aIns.getConceptOf().getID();
      
      System.out.println( "\n is this an ID?: "+ idSt);
      System.out.println( "\n is this an integer?: "+ _idIndx.get(idSt));

      i= Integer.parseInt((String)_idIndx.get(idSt));
	  	_conCm.setSelectedIndex(i);
	}
	
	private JPanel getRelationPanel(){
		JPanel relnsPanel= new JPanel();
   	_indxIDRel = new HashMap();
   	_idIndxRel = new HashMap();
		
		
      String allActRle[] = _dMRelat.getAllActionRelations();
      int numberRel =allActRle.length; 
      relnsPanel.setLayout(new GridLayout(numberRel,2));
      String relName;
		TreeMap reActInstances = _aIns.getActionRelations();    
		for (int j = 0; j < numberRel; j++) {
			relName = allActRle[j];
      		_indxIDRel.put(relName,new HashMap() );
      		_idIndxRel.put(relName,new HashMap() );;
			relnsPanel.add(new JLabel(relName));
			relnsPanel.add(getEInsCm(relName,
				(EntityInstance)reActInstances.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 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(_aIns.getNote());
     	_noteA.setRows(4);	//4 rows of text
     	_noteA.setLineWrap(true);	//line wrapped
     	_noteA.setWrapStyleWord(true);	//line wrapped at word bundaries
     	
     	//add default keymap to the textarea, so that Ctrl-c and v can
     	// be used for copy and past
     	
     	JTextField tf= new JTextField();
     	_noteA.setKeymap(tf.getKeymap());
     	
     	JScrollPane scrollP= new JScrollPane(_noteA);
     	scrollP.setHorizontalScrollBarPolicy(
          JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
     	scrollP.setVerticalScrollBarPolicy(
          JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
          
      notePanel.add(scrollP, BorderLayout.CENTER);
     	return notePanel;	
      
	}
	
	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 _aIns	
				onOKBotton();
			}else onCancelB();
		}

	}
	
	private void onOKBotton(){
		_OkButtonPressed= true;
		_CancelButtonPressed= false;
		System.out.println( "\n Ok button pressed");
		
		// update Action instance attributes
     	_aIns.setName(_nameT.getText());
     	int conIndex= _conCm.getSelectedIndex();
     	String indexSt= Integer.toString(conIndex);
     	DmConcept conA	= _dMM.getConcept((String)(_indxID.get(indexSt)));
     	if ( conA != null)
     		_aIns.setConceptOf(conA);
     		
     	_aIns.setDirty(_dirtyC.isSelected());
     	_aIns.setPreModifier(_premT.getText());
     	_aIns.setPostModifier(_postmT.getText());

     	_aIns.setNote(_noteA.getText());
     	
     	updateRel();
      
      //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.getActionRelations();    
		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);
			}
    	}
    	
		
	}
	
	
	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 _aIns.getName();
	}
	
	
}