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

import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.lang.Integer;
import java.awt.*;
import javax.swing.text.BadLocationException;
import parser.FSParser.*;
import taskModellingTool.*;
import domainModel.*;
import javax.swing.event.*;
import utility.*;


/********************************************
 * An extended range slider with extra functionality for the parser
 */
public class NewEInstance extends RangeSlider {

	private JTextArea _textfield= new JTextArea();
  
  	////Shijian 2001-1-23
  	private XManager _xManager = FileManager.getXDM();     // grab the xmanager
  	private DmManager _dMM=_xManager.getDmManager();	// default _dMM 
  
   	private JPopupMenu _popMenu = new JPopupMenu();
  	private JMenuItem _setHead = new JMenuItem("Set Head");
  	private JMenuItem _removeHead = new JMenuItem("Remove Head");
  	
	private JFrame  _parent = null; //default parent
	private JOptionPane  _pane ;
	private JDialog _dmDialog;
	private String  _type = null; 
	private String  _head = null; 

	private boolean _ok = false;
	
  	// constructor
  	public NewEInstance(JFrame parent, String name, String title,String type) {
	    super("", 0.0f, 500.0f);
	    
		_parent =parent;
	    _textfield.setText(name);
	    _type = type;
	    
		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();
	      	}
	    });
	}
	
	
	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 = _textfield.getSelectedText();
		if (select != null && (!( select.equals(""))))
	        _popMenu.add(_setHead);  
		
		return;	
	}

   	private void setHead() {
	  	int[] headArray = new int[2];
	
	    int start = _textfield.getSelectionStart();
	    int end = _textfield.getSelectionEnd();
		_head = _textfield.getSelectedText();
	    
	    headArray[1] = end;
	    headArray[0] = start;
	        
	    setHeads(headArray);
	    repaint();
  	}
  
  	private void removeHead() {
  		return;
  	}
  
	private JPanel getFieldsPanel(){
		
  		JPanel parsePanel = new JPanel();
    	_textfield.setRows(1);

      	_textfield.setColumns(500);
  		_textfield.setFont(new java.awt.Font("Monospaced", 0, 12));
    	_textfield.addMouseListener(mosueListener);		

		JScrollPane mainScrollPane = new JScrollPane();
  		Box box1;
    	Component component1 = Box.createVerticalStrut(8);
    	box1 = Box.createVerticalBox();
	    box1.add(_textfield, null);
	    box1.add(component1, null);
	    
    	box1.add(this, null);
    	
	    mainScrollPane.setHorizontalScrollBarPolicy(JScrollPane.
	    	HORIZONTAL_SCROLLBAR_NEVER);
     	mainScrollPane.setVerticalScrollBarPolicy(
          JScrollPane.VERTICAL_SCROLLBAR_NEVER);
	    mainScrollPane.setPreferredSize(new Dimension(400, 45));
    	//mainScrollPane.setPreferredSize(new Dimension(400, 65));
	    mainScrollPane.getViewport().add(box1, null);

	    parsePanel.setLayout(new FlowLayout());
     	parsePanel.add(mainScrollPane, null);
     	
     	return parsePanel;	
      
	}
	
 
	private void onButtonPress(){
		
		Object selectedValue = _pane.getValue();
		if (selectedValue != null && selectedValue != JOptionPane.UNINITIALIZED_VALUE){
			Integer sv = (Integer)selectedValue;
			
			if( sv.intValue()  == JOptionPane.OK_OPTION) {
		    	onOKBotton();
				
			}else onCancelB();
		}

	}
	
	private void onOKBotton(){
		_ok= true;
		
		createEI();
	}
	
	private void onCancelB(){
		_ok= false;
	}
	
	private void createEI(){
		String name = _textfield.getText();
		if (name.trim().length() <1) return;
		
		Sentence se = new Sentence(name);
		String premod= "";
		String postmod= "";
		
		String head="";
		
		if (_head != null && !(_head.equals("")))
			head=_head.trim();
			
		//if head is not specified, then take last word as head
		if (head.length() <1){
			head = name;
			if (se.getWordCount() > 1){
				premod = se.getAllWordsButLast();
				head = se.getLastWord();
			}
		}
		else {	//if head is specified
			premod = se.getAllWordsBefore(head);
			postmod = se.getAllWordsAfter(head);
		}
		
		//now create the entity instance
		EntityInstance ei ;
		if (_type.equals(ConceptType.getInterfaceType())){
			ei= new InterfaceInstance(name);
			if (premod != null && !(premod.equals("")))
				ei.setLabel(premod);	//if it is interface instance
									 // take premodifier as label
		}
		else {
			ei= new EntityInstance(name);
			if (premod != null && !(premod.equals("")))
				ei.setPreModifier(premod); 
		}
		_dMM.addEInstance(ei);

		if (postmod != null && !(postmod.equals("")))
			ei.setPostModifier(postmod);

		//create a concept of the head
		DmConcept dc = _dMM.getEConcept(head, _type);
		if (dc == null)
	  		dc = newEC(head,_type);
		ei.setConceptOf(dc); 
		
		_head = "";
	}
	
	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;
	}
	/**
	 * @return void
	* test the class.
	*/
	public static void main(String args[]) {
    	NewEInstance newEC = new NewEInstance(null, 
    		"new test", 
    			"Create new Object Instance",
    				"defsaulttype");
	}
    	
}