/*
   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.*;
import parser.FSParser.*;
import parser.slider.*;
import utility.*;


public class DMNameNew {
	//define range for _mode
	public final static int UNDER_FLOW = -1;
	public final static int NEW_ENTITY_CONCEPT = 0;
	public final static int NEW_SYSTEM_CONCEPT = 1;
	public final static int NEW_USER_CONCEPT = 2;
	public final static int NEW_INTERFACE_CONCEPT = 3;
	
	public final static int NEW_ACTION_CONCEPT = 4;
	public final static int NEW_ENTITY_INSTANCE = 5;
	public final static int NEW_SYSTEM_INSTANCE = 6;
	public final static int NEW_USER_INSTANCE = 7;
	
	public final static int NEW_ACTION_INSTANCE = 8;
	public final static int NEW_ENTITY_RELATION = 9;
	public final static int NEW_ACTION_RELATION = 10;
	
	public final static int OVER_FLOW = 11;	//6;

	//define Title to be used in the dialod box
	private static String TITLE_ENTITY_CONCEPT = 
			"New Object Concept";
	private static String TITLE_SYSTEM_CONCEPT = 
			"New System Concept";
	private static String TITLE_USER_CONCEPT = 
			"New User Concept";
	private static String TITLE_INTERFACE_CONCEPT = 
			"New Interface Concept";
	private static String TITLE_ACTION_CONCEPT = 
			"New Action Concept";
	private static String TITLE_ENTITY_INSTANCE = 
			"New Object Instance";
	private static String TITLE_SYSTEM_INSTANCE = 
			"New System Instance";
	private static String TITLE_USER_INSTANCE = 
			"New User Instance";
	private static String TITLE_ACTION_INSTANCE = 
			"New Action Instance";
	private static String TITLE_ENTITY_RELATION = 
			"New Entity Relation";
	private static String TITLE_ACTION_RELATION = 
			"New Action Relation";
	private static String TITLE[] = {
			TITLE_ENTITY_CONCEPT,
			TITLE_SYSTEM_CONCEPT,
			TITLE_USER_CONCEPT,
				TITLE_INTERFACE_CONCEPT,
			TITLE_ACTION_CONCEPT,
			TITLE_ENTITY_INSTANCE,
			TITLE_SYSTEM_INSTANCE,
			TITLE_USER_INSTANCE,
			TITLE_ACTION_INSTANCE,
			TITLE_ENTITY_RELATION,
			TITLE_ACTION_RELATION};
			
	//define examples to be used in the dialod box
	private static String EXAMPLE_ENTITY_CONCEPT = 
			"E.g., button";
	private static String EXAMPLE_SYSTEM_CONCEPT = 
			"E.g., ATM";
	private static String EXAMPLE_USER_CONCEPT = 
			"E.g., editor";
	private static String EXAMPLE_INTERFACE_CONCEPT = 
			"E.g., window";
	private static String EXAMPLE_ACTION_CONCEPT = 
			"E.g., do";
	private static String EXAMPLE_ENTITY_INSTANCE = 
			"E.g., a blue button";
	private static String EXAMPLE_SYSTEM_INSTANCE = 
			"E.g., that ATM";
	private static String EXAMPLE_USER_INSTANCE = 
			"E.g., that editor";
	private static String EXAMPLE_ACTION_INSTANCE = 
			"E.g., user press a blue button";
	private static String EXAMPLE_ENTITY_RELATION = 
			"E.g., part of";
	private static String EXAMPLE_ACTION_RELATION = 
			"E.g., actor";
	private static String EXAMPLES[] = {
			EXAMPLE_ENTITY_CONCEPT,
			EXAMPLE_SYSTEM_CONCEPT,
			EXAMPLE_USER_CONCEPT,
				EXAMPLE_INTERFACE_CONCEPT,
			EXAMPLE_ACTION_CONCEPT,
			EXAMPLE_ENTITY_INSTANCE,
			EXAMPLE_SYSTEM_INSTANCE,
			EXAMPLE_USER_INSTANCE,
			EXAMPLE_ACTION_INSTANCE,
			EXAMPLE_ENTITY_RELATION,
			EXAMPLE_ACTION_RELATION};

	//define labels to be used in the dialod box
	private static final String _name = "Please Enter Name  ";
	
	private static XManager _xManager = FileManager.getXDM();     // grab the xmanager
	private static DmManager _dMM=_xManager.getDmManager();	// default _dMM
  	private static Parser _actionParser = 
  					new Parser(_dMM,"action.grammar");; //  parsers
  	private static ParseFrame _slider= new ParseFrame(MainFrame.getMainFrame());           // the parser interface

  	private int _mode;
	private JTextField _nameT;
	private String _title = "";	//default dialog box title

	private JFrame  _parent = null; //default parent
	private JOptionPane  _pane ;
	private JDialog _dmDialog;
	private	JPanel _englishCard;

	private boolean  _OkButtonPressed= false;
	private boolean  _CancelButtonPressed= false;
	
   	private JPopupMenu _popMenu = new JPopupMenu();
  	private JMenuItem _setHead = new JMenuItem("Set Head");
  	private JMenuItem _removeHead = new JMenuItem("Remove Head");
   
	public DMNameNew(JFrame parent,int mo ) throws UnknownDMClassException{
		super();
		_parent =parent;
		_mode = mo;
		
		if (_mode > UNDER_FLOW && _mode < OVER_FLOW)
			_title = TITLE[_mode];
		else {
			throw new UnknownDMClassException();
		}
		
		//addMenuItemListener();
		_pane = new JOptionPane(getFieldsPanel(),
    		JOptionPane.PLAIN_MESSAGE,JOptionPane.OK_CANCEL_OPTION);
	   	_dmDialog = _pane.createDialog(_parent, _title);
		_dmDialog.show();
		
		onButtonPress();
	}
	/*
	private void addMenuItemListener(){
	   _setHead.addActionListener(new java.awt.event.ActionListener() {
	      	public void actionPerformed(ActionEvent e) {
				setHead();
	      	}
	    });
    
	   _removeHead.addActionListener(new java.awt.event.ActionListener() {
	      	public void actionPerformed(ActionEvent e) {
	      		removeHead();
	      	}
	    });
	}
   */
   
	private JPanel getFieldsPanel(){
		JPanel fieldPanel= new JPanel();
		//Dimension notePanelD= new Dimension(400,100);
	    //notePanel.setPreferredSize(notePanelD);
	      
	    fieldPanel.setLayout(new BorderLayout());
			
	    fieldPanel.add(new JLabel(_name),BorderLayout.WEST);
     	_nameT = new JTextField();
     	
     	_nameT.addMouseListener(mosueListener);		

      	fieldPanel.add(_nameT, BorderLayout.CENTER);
      	fieldPanel.add(new JLabel(EXAMPLES[_mode]), BorderLayout.SOUTH);
     	return fieldPanel;	
      
	}
	
	MouseListener mosueListener = new MouseAdapter(){
    	public void mousePressed(MouseEvent e) {
			maybeShowPopup(e);
		}	

		public void mouseReleased(MouseEvent e) {
		  	maybeShowPopup(e);
		}
		
		public void maybeShowPopup(MouseEvent e) {
			
			if (e.isPopupTrigger()) {
				constructMenu();
		        _popMenu.show(e.getComponent(),
		        e.getX(), e.getY());
		    }
		}

	};
	
	private void constructMenu(){
		_popMenu.removeAll();  
		
		String select = _nameT.getSelectedText();
		if (select == null){
			_popMenu.add(_removeHead);  
		
		}else{
			_popMenu.add(_setHead);
			_popMenu.add(_removeHead);  

		}
		return;	
	}
 
	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	
		     	try{
		    		onOKBotton();
		    	}catch( UnknownDMClassException e ) {
		         System.err.println( "Unrecognized domain class! " + e );
		      	}
				
			}else onCancelB();
		}

	}
	
	private void onOKBotton()throws UnknownDMClassException{
		_OkButtonPressed= true;
		_CancelButtonPressed= false;
	//	System.out.println( "\n Ok button pressed");
		String str = _nameT.getText();
      	if (str == null || str.equals("")){
 		 	nameNil();
 		 	return;
      	}
	    switch( _mode ) {
	         case NEW_ENTITY_CONCEPT:
	         	createEC(str, ConceptType.getDefaultEntityType());
	            break;
	         case NEW_SYSTEM_CONCEPT:
	         	createEC(str, ConceptType.getDefaultSystemType());
	            break;
	         case NEW_USER_CONCEPT:
	         	createEC(str, ConceptType.getDefaultUserType());
	            break;
	         case NEW_INTERFACE_CONCEPT:
	         	createEC(str, ConceptType.getInterfaceType());
	            break;
	         case NEW_ACTION_CONCEPT:
	         	createAC();
	            break;
	         case NEW_ENTITY_INSTANCE:
	         	createEI(str, ConceptType.getDefaultEntityType());
	            break;
	         case NEW_SYSTEM_INSTANCE:
	         	createEI(str, ConceptType.getDefaultSystemType());
	            break;
	         case NEW_USER_INSTANCE:
	         	createEI(str, ConceptType.getDefaultUserType());
	            break;
	         case NEW_ACTION_INSTANCE:
	         	createAI();
	            break;
	         case NEW_ENTITY_RELATION:
	         	createER();
	            break;
	         case NEW_ACTION_RELATION:
	         	createAR();
	            break;
	         default : // unrecognized domain class
	            throw new UnknownDMClassException();
	    }
	    
		
	}
	
	private void onCancelB(){
		_OkButtonPressed= false;
		_CancelButtonPressed= true;
		System.out.println( "\n Cancel button pressed");

	}
	
	public boolean isOKButton(){
		return _OkButtonPressed;
	}
	
	public boolean isCancelButton(){
		return _CancelButtonPressed;
	}
/*	
	private void createEC(){
		System.out.println( "\n create entity concept");
	  	DmConcept dc = createEC(_nameT.getText());
	  	
	  	// now modify the concept if you wish
	 	EConceptEdit ad = new EConceptEdit(MainFrame.getMainFrame(),
	 		"Edit Entity Concept",dc);
    	if (ad.isOKButton())
    		System.out.println("\n YEs, it is OK " );
	}
*/
	private DmConcept createEC(String name, String type){
	  	DmConcept dc = newEC( name,  type);
	  	
		// now modify the concept if you wish
	 	//EConceptEdit ad = new EConceptEdit(MainFrame.getMainFrame(),
	 	//	"Edit Entity Concept",dc);
	 	return dc;
	}
	
/*	private void createUC(){
		//System.out.println( "\n create entity concept");
	  	//DmConcept dc = createEC(_nameT.getText());
	  	DmConcept dc = new DmConcept(_nameT.getText(), 
	  		ConceptType.getDefaultUserType()); 
	 
	  	//add language card to DmManager collection
	  	_dMM.addEnglishN((EnglishNoun)dc.getCard(DmConcept._ENGLISH));
	  	_dMM.addConcept(dc);
	  		  	
	  	// now modify the concept if you wish
	 	EConceptEdit ad = new EConceptEdit(MainFrame.getMainFrame(),
	 		"Edit Entity Concept",dc);
	}
*/	
	private void createAC(){
		System.out.println( "\n create action concept");
	  	DmConcept dc = new DmConcept(_nameT.getText(), ConceptType.getDefaultActionType()); //"entity type");
	 
	  	//add language card to DmManager collection
	  	_dMM.addEnglishV((EnglishVerb)dc.getCard(DmConcept._ENGLISH));
	  
	  	dc.setParent(DmConcept.getDefaultActionConcept());
	  	_dMM.addConcept(dc);
	  	
	  	// now modify the concept if you wish
	 	AConceptEdit ad = new AConceptEdit(MainFrame.getMainFrame(),
	 		"Edit Entity Concept",dc);
    	if (ad.isOKButton())
    		System.out.println("\n YEs, it is OK " );
	}
	
	private void createEI(String name, String type){
		//String name = _nameT.getText();
		Sentence se = new Sentence(name);
		String premod= "";
		String head = name;
		if (se.getWordCount() > 1){
			premod = se.getAllWordsButLast();
			head = se.getLastWord();
		}
		
		//now create the entity instance
		EntityInstance ei = new EntityInstance(name);
		_dMM.addEInstance(ei);

		if (premod != null && !(premod.equals("")))
			ei.setPreModifier(premod);
		//create a concept of the head
	  	DmConcept dc = newEC(head,type);
		ei.setConceptOf(dc); 
		
	  	// now modify the instance if you wish
	 	EInstanceEdit ed = new EInstanceEdit(MainFrame.getMainFrame(),
	 		"Edit Entity Instance",ei);
    	if (ed.isOKButton())
    		System.out.println("\n YEs, it is OK " );
	}

/*	
	private void createEI(){
		System.out.println( "\n create entity instance");
	
		StringBuffer stbPre = new StringBuffer();
		
		String deliminator = " ";
		String stTemp,premod="";
		String head="";
		
		//first parse the text
		// make the last word as head and 
		//all rest as premodifier
		String name = _nameT.getText();
		StringTokenizer stk = new StringTokenizer(name);
		int counter = stk.countTokens();
		int i = 1;
		
		if (stk.hasMoreTokens()){
			stTemp =stk.nextToken() ;
			stbPre.append(stTemp);
			head = stTemp;
		}
			
		while (stk.hasMoreTokens()){
			stTemp =stk.nextToken() ;
			
			if (++i != counter){
				stbPre.append(deliminator);
				stbPre.append(stTemp);
			} else {
				head = stTemp;
				
			}
		}
		premod = stbPre.toString();
		
		//now create the entity instance
		EntityInstance ei = new EntityInstance(name);
		if (premod != null && !(premod.equals("")))
			ei.setPreModifier(premod);
		//create a concept of the head
	  	DmConcept dc = createEC(head);
		ei.setConceptOf(dc); 
		
	  	// now modify the instance if you wish
	 	EInstanceEdit ed = new EInstanceEdit(MainFrame.getMainFrame(),
	 		"Edit Entity Instance",ei);
    	if (ed.isOKButton())
    		System.out.println("\n YEs, it is OK " );
	}
*/	
	private void createAI(){
		//System.out.println( "\n create action instance");
	    boolean returnCode = _actionParser.parse(_nameT.getText());
	  	String title = "Create a new Action Instance";
	    _slider.run(_actionParser, _dMM,title, null);
	}
	
	private void createER(){
		//System.out.println( "\n create entity relation");
		DmRelation.getInstance().addEntityRelation(_nameT.getText());

	}
	
	private void createAR(){
		//System.out.println( "\n create action relation");
		DmRelation.getInstance().addActionRelation(_nameT.getText());
	}

	
	private void nameNil(){
		Object[] options = { "OK" };
     	int opt = JOptionPane.showOptionDialog(null, "Name cannot be empty!!", "Warning", 
               JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
               null, options, options[0]);

        return;
	}
	
	private DmConcept newEC(String name, String type){
	  	DmConcept dc = new DmConcept(name, type);
	 
	  	//add language card to DmManager collection
	  	_dMM.addEnglishN((EnglishNoun)dc.getCard(DmConcept._ENGLISH));
	  	_dMM.addConcept(dc);
	  		  		  	
	  	return dc;
	}
	private void setHead(){
		return;
		
	}
	private void removeHead(){
		return;
		
	}
}