/*
   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/.

   Redistribution in source and binary forms, with or without modification, are not permitted.
   
   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.
*/

// to do:
//  fix the task edit dialog box (remove semantics field)
//  start parser instead
//  pass the modified task name to the parse if there are no semantics.
//  set the semantics string for the task
//  change parser to default to the old parsing behavior.
//  modify the slider window to implement new interface.


package taskModellingTool;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.reflect.*;
import java.util.*;
import javax.swing.tree.*;

// Here comes the parser - kvlinden, 5jan2001
import domainModel.*;
import parser.FSParser.*;
import parser.slider.*;
import domainModel.gui.*;


public class EditionDialog{
	
  	// stuff for the CNL parser - kvlinden, 5jan2001
  	//20-2-2002
  	//private static Parser defaultParser, actionParser, stateParser; // 3 parsers
  	//private static ParseFrame slider;     // the parser interface
  	//private static DmManager dmManager;   // the domain model?
  	//private static XManager xManager;     // the XML reader/printer?

    private static final int MARGINX=5;
    private static final int MARGINY=5;
    private static final int GAPX=10;
    private static final int GAPY=5;
    private static final int SIZEX1=80;
    private static final int SIZEX2=250;
    private static final int SIZEXOK=60;
    private static final int SIZEXCANCEL=80;
    private static final int SIZEY=20;
    
    private static final Color BACKGROUND_COLOR=null;//Color.white;
    //private static final Color BACKGROUND_COLOR=new Color(255,255,255);
    
    protected static JDialog dialog;

    private GenericComponent currentClass=null;
    
    private boolean abort=false;
    
    private boolean modifyItself=true;
    
    private String oldName=null;
    
    protected static JComponent [] jComp;
    
    protected static Field [] fields;
    
    private String oldSemantics="";
	//shijian 18-1-2001
    private JTextField _JTFSemantics=null;
	//shijian 18-1-2001
    private String _taskName ="";
 	//shijian 15-2-2001
    private String _taskStyle="";
    
    //shijian 2001-3-29
    private boolean _nameModified=false;
    private boolean _preconModified=false; //for task and link
    private boolean _feedbackModified=false;
    private boolean _actorModified=false;
  
    //protected static DomainAction taskDiaActionBuff;
/*           
    public EditionDialog(GenericComponent gc){
    	String name =gc.getName();
      	currentClass=gc;
        
    	String [] options={"OK","Cancel"};
    	int n=JOptionPane.showOptionDialog(MainFrame.mainFrame,createPanel(),
    	    "Edit",JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE,null,options,options[0]);

    	if (n == JOptionPane.OK_OPTION) performModification();
    }
*/    
    public EditionDialog(GenericComponent gc, boolean duplicatedTaskNameAllowed) {

        // stuff for the parser interface - kvlinden, 5jan2001
        //20-2-2002
        //xManager = FileManager.getXDM();     // grab the x manager
        //dmManager = xManager.getDmManager(); // grab the dm manager
        
        //20/2-2002
        //defaultParser = new Parser(dmManager,"simple.grammar"); // for 3-word expressions
        //actionParser = new Parser(dmManager,"action.grammar");  // for general action expressions
        //      stateParser = new Parser(dmManager,"state.grammar"); // for state expressions
        //slider = new ParseFrame(MainFrame.mainFrame);           // the parser interface
        
        

    	String name = gc.getName();
        currentClass = gc;
    	JOptionPane pane = new JOptionPane(createPanel(),
    		JOptionPane.PLAIN_MESSAGE,JOptionPane.OK_CANCEL_OPTION);
    	dialog = pane.createDialog(MainFrame.mainFrame, "Edit [" + name + "]");
        
        boolean nameOK = true;
        boolean recursiveTaskFlag = false;
        boolean duplicatedTaskFlag = false;
        boolean okSelectedFlag = true;
        String newName;
        String oldName = name;
        Integer id2 = new Integer(gc.ID);
        do {
            dialog.show();
            
            newName = getName(pane);
            okSelectedFlag = checkIfOKSelected(pane);
            //TMUtility.display("EditionDialog : okSelectedFlag",okSelectedFlag);
            
            if (currentClass instanceof Task) {
                if (okSelectedFlag) {
                    nameOK = checkIfNameOK(newName);
                    recursiveTaskFlag = Manager.skeleton.checkIfRecursiveTask(oldName,newName);
                    
                    if (!duplicatedTaskNameAllowed) {
                        if (!oldName.equals(newName))
                            duplicatedTaskFlag = Manager.skeleton.isInRegister(newName);
                    }
                }
                else {
                    nameOK = true;
                    recursiveTaskFlag = false;
                    duplicatedTaskFlag = false;
                    abort = true;
                }
            }
            
            if (!nameOK) {
                JOptionPane.showMessageDialog(MainFrame.mainFrame,
                    "Task name ["+newName+"] must not be empty or contain the following restricted characters : \n\n"+
                    "\\  /  :  \"  ?  *  <  >  |\n", "Error - Invalid Name", JOptionPane.ERROR_MESSAGE);
                    
                pane.setValue(JOptionPane.UNINITIALIZED_VALUE);
            }
            
            if (recursiveTaskFlag) {
                JOptionPane.showMessageDialog(MainFrame.mainFrame,
                    "The new task name ["+newName+"] is the same as the task name of \n"+
                    "one of its parent(s) or its children.\n\n"+
                    "Currently recursive tasks are not supported yet.\n\n",
                    "Error - Invalid Name", JOptionPane.ERROR_MESSAGE);
                    
                pane.setValue(JOptionPane.UNINITIALIZED_VALUE);
            }
            
            if (duplicatedTaskFlag) {
                JOptionPane.showMessageDialog(MainFrame.mainFrame,
                    "The new task name ["+newName+"] is already used.\n"+
                    "Duplicated task is not allowed for this function.\n\n"+
                    "Please enter another name.\n\n",
                    "Error - Invalid Name", JOptionPane.ERROR_MESSAGE);
                    
                pane.setValue(JOptionPane.UNINITIALIZED_VALUE);
            }
        } while ((!nameOK) || (recursiveTaskFlag) || (duplicatedTaskFlag));
        
        if (okSelectedFlag) {
            performModification();
        }
        
        DomainModelManager.oldActionName="";
        DomainModelManager.actionBuff=null;
    }
    
    private String getName(JOptionPane pane) {
        String result = null;
        
        for (int i=0;i<fields.length;i++) {
            if ((fields[i].getName()).equals("name")) {
               result = ((JTextField)jComp[i]).getText();
               
               break;
            }
        }
        
        return result;
    }
    
    private boolean checkIfOKSelected(JOptionPane pane) {
        boolean result = false;
        
        Object selectedValue = pane.getValue();
        if (selectedValue != null && selectedValue != JOptionPane.UNINITIALIZED_VALUE) {
            if (selectedValue instanceof Integer){
                Integer sv = (Integer)selectedValue;
                if(sv.intValue()  == JOptionPane.OK_OPTION) {
                    result = true;
                }
            }
        }
        
        return result;
    }
    
    private boolean checkIfNameOK(String name) {
        if (name.equals("")) return false;
        
        if (!checkIfNameOK(name,"\\")) return false;
        if (!checkIfNameOK(name,"/")) return false;
        if (!checkIfNameOK(name,":")) return false;
        if (!checkIfNameOK(name,"\"")) return false;
        if (!checkIfNameOK(name,"?")) return false;
        if (!checkIfNameOK(name,"*")) return false;
        if (!checkIfNameOK(name,"<")) return false;
        if (!checkIfNameOK(name,">")) return false;
        if (!checkIfNameOK(name,"|")) return false;
        
        return true;
    }
    
    private boolean checkIfNameOK(String name,String restrictedCharacter) {
        boolean result = true;
        
        int index = name.lastIndexOf(restrictedCharacter);
        if (index >= 0) {
            result = false;
        }
        
        return result;
    }

    private String getTaskName() {
        String result = "";

        for (int i=0;i<fields.length;i++) {
            String name = fields[i].getName();
            if (name.equals("name"))
                result = ((JTextField)jComp[i]).getText();
        }
        
        return result;
    }
    
    private void performModification() {
    	if (okForModification(fields,jComp)) {
        	String taskName = getTaskName();

            if (!(taskName.equals(oldName)) && currentClass instanceof Task) 
            	updateLinkParent(taskName); 
            	
   	        for (int i=0;i<fields.length;i++)	{
    			String type = fields[i].getType().getName();
        		String name = fields[i].getName();
    	        		
				//Shijian 19-1-2001
				// skip over semantics
				 if (name.equals("semantics")) continue;

				//Shijian 8-2-2001
				// get hold of new task name
				 if (name.equals("name"))
   	         		_taskName=((JTextField)jComp[i]).getText();
   					 
                if (name.equals("style")) {
                	
                	//shijian 2001-2-15
                    //String style = (String) (((JComboBox)jComp[i]).getSelectedItem());
	  			    //System.err.println("@@@@@@@@@@Task style = " +_taskStyle);
	                if (!(_taskStyle.equals(""))){
	                	try {
	                        fields[i].set(currentClass,_taskStyle);
	                    }
	                    catch (Exception except) {}
	                    
	                    ((Task)currentClass).setSemantics("");
	                    _taskStyle="";
	                }
                }
    	        else if (type.equals("java.lang.String")) {
    	        	
    	        	//shijian 2001-3-28
    	        	if (currentClass instanceof Link){
    	        		Link l = (Link)currentClass;
     		        	if (name.equals("condition")){ 
     		        		l.setPrecondition(((JTextField)jComp[i]).getText());
     		        	}
     		        	else {
		    	        	try {
		   	                	fields[i].set(currentClass,((JTextField)jComp[i]).getText());
			   	            }
			   	            catch (Exception except){}
     		        	}
    	        	}
    	        	else if (currentClass instanceof Task){
    	        		Task t = (Task) currentClass;
	    	        	if (name.equals("name") && _nameModified){
	    	        		t.setSemantics("");
		    	        	try {
		   	                	fields[i].set(currentClass,((JTextField)jComp[i]).getText());
			   	            }
			   	            catch (Exception except){}
	    	        	}
	    	        	else if (name.equals("precondition") && _preconModified){
	    	        		t.setPrecon(((JTextField)jComp[i]).getText());
	    	        	}
	    	        	else if (name.equals("feedback") && _feedbackModified){
	    	        		t.setFeedback(((JTextField)jComp[i]).getText());
	    	        	}
	    	        	else if (name.equals("actor") && _actorModified){
	    	        		t.setActor(((JTextField)jComp[i]).getText());
	    	        	}
	    	        	else {
		    	        	try {
		   	                	fields[i].set(currentClass,((JTextField)jComp[i]).getText());
			   	            }
			   	            catch (Exception except){}
	    	        	}
    	        	}
    	        	else{
	    	        	try {
	   	                	fields[i].set(currentClass,((JTextField)jComp[i]).getText());
		   	            }
		   	            catch (Exception except){}
    	        	}
	        	}
	        	else if (type.equals("int")) {
    	            int nb=-1;
                    try {
                    	nb=Integer.parseInt(((JTextField)jComp[i]).getText());
             	        if (nb<0) nb=-1;
                    }
                    catch (NumberFormatException excep){}
   	                try {
   	                	fields[i].setInt(currentClass,nb);
  	                }
  	                catch (Exception except){}
    	        }
    	        else if (type.equals("boolean")) {
   	            	try {
   	                	fields[i].setBoolean(currentClass,((AbstractButton)jComp[i]).isSelected());
   	                }
   	                catch (Exception except) {}
   	            }
   	        }
        }
        
   	    FileManager.MODIFIED = true;         
   	    currentClass.repaint();
   	    
   	    //shijian 2001-3-29
    	_nameModified=false;
    	_preconModified=false;
    	_feedbackModified=false;
    	_actorModified=false;
    }
    
    private JPanel createPanel() {
    	GenericComponent gc = currentClass;
    	JPanel panel = new JPanel();
    	JButton editB = new JButton("Edit Semantics");
    	editB.setRequestFocusEnabled(false);
        panel.setBackground(BACKGROUND_COLOR);
        panel.setFont(new Font("Helvetica", Font.PLAIN, 14));        
    	panel.setLayout(null);
        
    	if (gc != null) {
            Class cl = gc.getClass();
    	    Object [] obj = gc.getDialogsFields();
    	    jComp = new JComponent[obj.length];
    	    fields = new Field[obj.length];
    	    JComponent jc;
    	    Field field;
            String fieldName;
    	    int posx = MARGINX;
    	    int posy = MARGINY;
    	    
    	    //shijian 2001-3-22
    	    if (Manager.systemOptions.domainModelFlag)
	    	    panel.setPreferredSize(new Dimension(MARGINX*2+GAPX+SIZEX2+SIZEXOK+SIZEXCANCEL-45,	//+5,    
	    	        MARGINY+(SIZEY+GAPY)*(obj.length+1)));
	    	else
	    	    panel.setPreferredSize(new Dimension(MARGINX*2+GAPX+SIZEX2+SIZEXOK+SIZEXCANCEL-45,    
	    	        MARGINY+(SIZEY+GAPY)*(obj.length+1-4)));

    	    for (int i=0;i<obj.length;i++) {
                try {
                    fieldName = (String) obj[i];
                    //System.out.println("fieldName = "+fieldName);
                    field = cl.getField(fieldName);
    		        fields[i] = field;
    		    
    		        if ((field.getName()).equals("name")) {
   	                    oldName = (String)field.get(gc);
                    }
                    else if ((field.getName()).equals("semantics")) {
                        String sem = (String)field.get(gc);

                        DomainModelManager.oldActionName = sem;  //(String)field.get(gc);
                        oldSemantics = sem;
                    }

                    //System.out.println("testing sm name1: "+ field.getName());
                	if(!(Manager.systemOptions.domainModelFlag) &&
                		(fieldName.equals("dirty") ||
                		fieldName.equals("warning") ||
                		fieldName.equals("actor") ||
                		fieldName.equals("other"))) 
                		continue;
                		
    		        jc = new JLabel(fieldName);
                    jc.setBounds(posx,posy,SIZEX1,SIZEY);
    		        	  posx += SIZEX1+GAPX;
                    panel.add(jc);
    
                    if (fieldName.equals("style")) {
                        jc = buildJComboBox(field,gc);
                        //jc.setBackground(Color.white);
                    }
                    else
                        jc = buildJComponent(field,gc);
    		        jc.setBounds(posx,posy,SIZEX2,SIZEY);
    		        
	        		if ((field.getName()).equals("name")){	// &&
	        			//	Manager.systemOptions.domainModelFlag) {
   	                	//editB.setBounds(posx+SIZEX2+GAPX,posy-5,SIZEXOK+SIZEXCANCEL,SIZEY+5*2);
	                    //	editB.addActionListener(new DmActionD());
	                    //	panel.add(editB);
	                    	
	                    	jc.setRequestFocusEnabled(true);
	                    	jc.requestFocus();

   	            	}
   	            	
   	            	//shijian 2001-3-29
   	            	//monitoring changes
     		        if (jc instanceof  JTextField &&
     		        	currentClass instanceof Task){ 
     		        	JTextField tf = (JTextField)jc;
     		        	if (fieldName.equals("name")){ 
					    	tf.addKeyListener(new KeyAdapter() {
					      		public void keyTyped(KeyEvent ke) {
	    							_nameModified=true;
					      		}
							});
	    		       	} 
	    		        else if (fieldName.equals("precondition") ){
					    	tf.addKeyListener(new KeyAdapter() {
					      		public void keyTyped(KeyEvent ke) {
	    							_preconModified=true;
					      		}
							});
    		       		} 
	    		        else if (fieldName.equals("feedback")) {
					    	tf.addKeyListener(new KeyAdapter() {
					      		public void keyTyped(KeyEvent ke) {
	    							_feedbackModified=true;
					      		}
							});
    		       		} 
	    		        else if (fieldName.equals("actor")) {
					    	tf.addKeyListener(new KeyAdapter() {
					      		public void keyTyped(KeyEvent ke) {
	    							_actorModified=true;
					      		}
							});
    		       		} 
     		        }
     		        else if (jc instanceof  JTextField &&
     		        	currentClass instanceof Link){ 
     		        	JTextField tf = (JTextField)jc;
     		        	if (fieldName.equals("condition")){ 
					    	tf.addKeyListener(new KeyAdapter() {
					      		public void keyTyped(KeyEvent ke) {
	    							_preconModified=true;
					      		}
							});
	    		       	} 
     		        }

    		    	posx = MARGINX;
	    	    	posy += SIZEY+GAPY;
		        	jComp[i] = jc;
		        	panel.add(jc);
                    
                }
                catch (Exception e) {
                    System.out.println("getField error");
                }
    	    }    	    
    	}
        return panel;
    }
    
    private JComponent buildJComboBox(Field field,GenericComponent gc) {
        JComponent result = null;
        
        String fieldValue = null;
        try {
            fieldValue = (String)field.get(gc);
        }
        catch (Exception e) {
            System.out.println("buildJComboBox error !");
        }
        
        String[] styleOptions = { Task.STYLE_VALUE[0], Task.STYLE_VALUE[1], Task.STYLE_VALUE[2] };
        
        // Create the combo box, select item at index, indices start at 0
         final JComboBox jc = new JComboBox(styleOptions);
        
        int index = 0;
        if (fieldValue.equals(Task.STYLE_VALUE[0])) index = 0;
        else if (fieldValue.equals(Task.STYLE_VALUE[1])) index = 1;
        else  index = 2;
        jc.setSelectedIndex(index);

        jc.setFont(new Font("Helvetica", Font.PLAIN, 14));        
        //shijian 2001-2-15
        //add actionlistener  void itemStateChanged(ItemEvent
		jc.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				_taskStyle = (String) (jc.getSelectedItem());
				//System.out.println("@@@@@@@@@@item changed!");
			}
		});


        result = jc;
        
        return result;
    }

    private JComponent buildJComponent(Field field,GenericComponent gc) {
    	String type = field.getType().getName();
    	JComponent result = null;
        
    	try {
    	    if (type.equals("java.lang.String")) {
    	    	 //shijian 18-1-2001
    	    	//donot display semantics filed
    	    //	if (!(field.getName()).equals("semantics")) {
            	//_JTFSemantics = jc;   //(String)field.get(gc);

    	    		final JTextField jc = new JTextField((String)field.get(gc));
                	jc.setFont(new Font("Helvetica", Font.PLAIN, 14));  
    	    		
    	    		//shijian 8-2-2001
    	    		// add keyListener to task name textfield to
    	    		// track text change
   	    		if ((field.getName()).equals("name")) {
   	    			_taskName = jc.getText();
   	        		jc.addKeyListener(new KeyAdapter() {
	      				public void keyReleased(KeyEvent ke) {
	      					_taskName = jc.getText();
	      				}
						});
					
					jc.selectAll();
					jc.requestFocus();
   	        		
   	    		}
    	    		result = jc;
    	    //	}
    	    }
    	    else if (type.equals("int")) {
    	    	int nb = field.getInt(gc);    	    	
    	    	JTextField jc;
    	    	if (nb>=0) jc = new JTextField(Integer.toString(nb));
    	    	else jc = new JTextField("");
                jc.setFont(new Font("Helvetica", Font.PLAIN, 14));        
    	    	result = jc;
    	    }
    	    else if (type.equals("boolean")) {
    	    	JCheckBox jc = new JCheckBox("",field.getBoolean(gc));
    	    	result = jc;
    	    }
    	}
        catch (Exception e) {
            System.out.println("buildJComponent error !");
        }
    	
        if (result!=null) {
    	    //result.setBackground(BACKGROUND_COLOR);
    	    //result.setForeground();
    	}
        
        return result;
    }
    
    private boolean okForModification(Field [] fields,JComponent [] jComp) {
   	for (int i=0;i<fields.length;i++) {
   		//Shijian 19-1-2001
   		// skip over semantics
   		 if ((fields[i].getName()).equals("semantics")) continue;
   		 
   	    if ((fields[i].getName()).equals("name")) {
   	        String newName=((JTextField)jComp[i]).getText();

   	        //search for duplicated tasks
   	        //Set keys=((TreeMap)Manager.skeleton.nodeRegister.get(oldName)).keySet();
            //int duplecateNo =  keys.size();
            int duplecateNo = Manager.skeleton.getNumDuplicatedTasks(oldName);

            if (!(oldName.equals(newName)) && Manager.skeleton.isInRegister(newName)) {
                 String [] options={"Modity this component","Modify the others","Cancel"};
                 String message="A task of the same name already exits.\nTo maintain coherence you can either modify this task \nor the other tasks of the same name.";
                 int choice=JOptionPane.showOptionDialog(MainFrame.mainFrame,message,
                 			"The component is going to be modified",
                 			JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,
                 			null,options,options[0]);

                 if (choice==0) modifyItself=true;
                 else if (choice==1) modifyItself=false;
                 else abort=true;
            }
            else if (duplecateNo > 1) {
                if (oldName.equals(newName)) {
                    modifyItself = false;     // modify others
                }
                else {
                    String [] options={"Modity this component","Modify the others","Cancel"};
    	            String message="There are other occurences of the same task.\nTo maintain coherence you can either modify this task \nor the other tasks of the same name.";
    	            int choice=JOptionPane.showOptionDialog(MainFrame.mainFrame,message,
    	          			"The component is going to be modified",
    	          			JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,
    	          			null,options,options[0]);

                    if (choice==0) modifyItself=true;
                    else if (choice==1) modifyItself=false;
                    else abort=true;
                }
            }
            else {
                abort=false;
                modifyItself=true;
            }
             

       /*

   	        if (newName.equals(oldName))
   	        {

  	            if ( duplecateNo == 1) 

                {
   	                abort=false;
   	                modifyItself=true;

                }
                else
                {
    	            String [] options={"Modity this component","Modify the others","Cancel"};
    	            String message="There are other occurences of the same task.\nTo maintain coherence you can either modify this task \nor the other tasks of the same name.";
    	            int choice=JOptionPane.showOptionDialog(MainFrame.mainFrame,message,"The component is going to be modified",JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null,options,options[0]);

                    if (choice==0) modifyItself=true;
                    else if (choice==1) modifyItself=false;
                    else abort=true;

                }
   	        }
   	        else if (Manager.skeleton.isInRegister(newName))
   	             {
    	            String [] options={"Modity this component","Modify the others","Cancel"};
    	            String message="A task of the same name already exits.\nTo maintain coherence you can either modify this task \nor the other tasks of the same name.";
    	            int choice=JOptionPane.showOptionDialog(MainFrame.mainFrame,message,"The component is going to be modified",JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null,options,options[0]);

                    if (choice==0) modifyItself=true;
                    else if (choice==1) modifyItself=false;
                    else abort=true;
   	             }
        */



   	    }
   	    if (abort) break;
   	}
   	return !abort;     	
    }
        
    public boolean isAborted(){
    	return abort;
    }
    
    public boolean willModifyItself(){
    	return modifyItself;
    }

//-----------------------------------------------------------------------------    
//Thomas
private boolean okForModification1(){ //Field [] fields,JComponent [] jComp){
	modifyItself=false;

   	for (int i=0;i<fields.length;i++) {
   		//System.out.println("Fields : "+fields[i].getName());
   	    if ((fields[i].getName()).equals("name")) {
   	        String newName=((JTextField)jComp[i]).getText();
	   		//System.out.println("    newName : "+newName);
   	    	
   	        //search for duplicated tasks
   	        Set keys=((TreeMap)Manager.skeleton.nodeRegister.get(oldName)).keySet();
            int duplecateNo =  keys.size();
			if (newName.equals(oldName)) {
   	            abort=false;
   	            modifyItself=false;
         	}
         	else if (Manager.skeleton.isInRegister(newName)) {
            	if (duplecateNo == 1) {
	                String [] options={"Modify","Cancel"};
	                String message="A task of the same name already exits.\nTo maintain coherence you can either modify the other tasks of \nthe same name or cancel the operation.";
	                int choice=JOptionPane.showOptionDialog(MainFrame.mainFrame,message,
	                 			"Modify tasks",
	                 			JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,
	                 			null,options,options[0]);
	
	                if (choice==0) modifyItself=false;
                 	else abort=true;
            	}
                else {
                	String [] options={"Modity this component","Modify the others","Cancel"};
	    	        String message1="There are multiple occurences of the task named " + oldName;
	    	        String message2= "\nand task named " + newName + " already exists. "; 
	    	        String message3= "\nthe operation cannot preceed.";
	    	        String message = message1+ message2+ message3;
	    	        JOptionPane.showMessageDialog(MainFrame.mainFrame, message,
	    	          	"Task modification", JOptionPane.WARNING_MESSAGE );	
	                abort=true;
                }
         	}
            else {
            	abort=false;
                modifyItself=true;
            }
   	    }
   	    if (abort) break;
  	}
   	return !abort;     	
 }
 
 
 
 private void updateLinkParent(String newName){
 	//System.out.println("old task name : " +    oldName	);

 	Node taskCom=Manager.skeleton.getFirstNode(oldName);

 	if (taskCom != null){
	 	Set keys=taskCom.keySet();
	   	Couple c,c2;
	   	Link ln;
	   	String brotherName;
	   	LinkedList list=new LinkedList();
	   
	    for (Iterator it=keys.iterator();it.hasNext();){
	        brotherName=(String)it.next();
	        c=taskCom.getCouple(brotherName);
	   	    if (c.object instanceof LinkableComponent){
	   	    	//System.out.println("task name : " +    brotherName	);
	   	    	//only for a CompositeComponent
    	    	if (brotherName.equals(oldName) && !c.node.isEmpty()){
    	    		//System.out.println("task name : " +    brotherName +" not empty"	);

    	    		Set keysChildren=((Node)c.node).keySet();
    	    		for (Iterator ite=keysChildren.iterator();ite.hasNext();){    	    				
    	    			String childName=(String)ite.next();
    	    			c2=((Node)c.node).getCouple(childName);
    	    			if (c2.object instanceof Link){
    	    				ln=(Link)c2.object;
    	    				ln.parentName=newName;
    	    			}
    	    			//System.out.println("compnent name : " +    childName	);
    	    		}
    	    	}	

	   	    }
	    }
 	}
 	
 	
 }
 
 //shijian 18-1-2001
 //set text for semantic texfild
 public void setSemantics(String str){
      if (currentClass instanceof Task){
      	Task t=(Task) currentClass;
      	t.semantics =str;
      }
 }
 
 //shijian 7-2-2001
 //construct semantics from task name
 private String getDefaultSemantics(){
 	 String seman= "";
 	 GenericComponent gc=currentClass;

    if (gc instanceof Task){
   	Task t=(Task) gc;
   	seman= t.semantics;
   	String tn = _taskName;
   	if (tn.equals(""))
   		tn = t.name;

		 // if no semantics, grab task name and add actor based on task type
	    // and pass that to the parser
			if (t.style.equals("Automatic"))
				seman = EntityInstance.getDefaultSystemInstance().getName()
					+" "+_taskName;
			else
				seman = EntityInstance.getDefaultUserInstance().getName()+
					" "+_taskName;		
		
    }
    return seman;
 }
 
 
 //shijian 13-2-2001
 // get task
 public Task getTask(){
      if (currentClass instanceof Task)
      	return ((Task) currentClass);
      else return null;
 }
 
 
 //20-02-1-2002
 /*
  class DmActionD implements ActionListener {
    public void actionPerformed(ActionEvent e){
      GenericComponent gc=currentClass;
      
      if (gc instanceof Task){
      	Task t=(Task) gc;
			// if semantics is not nil, get action instance name			
	     	String seman= t.semantics;
	     	ActionInstance aiTemp;
	      	if (!(seman == null || seman.equals(""))){
	      		if (dmManager.getAInstance(seman) != null){
	      			aiTemp = dmManager.getAInstance(seman);
       		 		seman= aiTemp.getName();
	      		}
       		}	
	      	if (seman == null || seman.equals(""))
     		 	seman= t.getDefaultSemantics();
     		 	
	  		String title = "Edit Semanitcs";
		    boolean returnCode = actionParser.parse(seman);
		    slider.run(actionParser, dmManager,title,currentClass); 	//EditionDialog.this);
     		  
		    if (currentClass != null && (currentClass instanceof Task)
		    	&& slider.isOK())
		    	((Task)currentClass).setSemantics(slider.getAI().getID());
		    	
			dmManager.printConcept(dmManager.getConceptAll());	
			dmManager.printAInstance(dmManager.getAInstanceAll());	
			System.out.println("Semantics : " + 	seman);
				 
      
      }
    }
  }
 */   
}