package extractor.ui.clusteringUI;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.io.*;
import javax.swing.tree.*;

import java.util.*;
import java.lang.*;

public class InputNode extends JPanel implements ActionListener
{
	JTextField field;
	JLabel label;
	JButton okBtn;
	JTree tree;
	private DefaultTreeModel treeModel;
	
	public InputNode(JTree t)
	{
		tree = t;
		treeModel = (DefaultTreeModel)tree.getModel();
		label = new JLabel("Cluster Name : ");
		field = new JTextField();
		label.setLabelFor(field);
		field.setPreferredSize(new Dimension(100, 30));
		okBtn = new JButton("OK");
		okBtn.addActionListener(this);
		add(label);
		add(field);
		add(okBtn);

		setVisible(true);
	}
	
	public void actionPerformed(ActionEvent ev) 
	{
		Object obj = ev.getSource();
		if(obj == okBtn)
		{
		        DefaultMutableTreeNode parentNode = null;	
		        DefaultMutableTreeNode child = new DefaultMutableTreeNode(field.getText());		
		        TreePath parentPath = tree.getSelectionPath();
		        boolean breakChk = false;
			
		        if (parentPath == null)
		        {
		            parentNode = (DefaultMutableTreeNode)tree.getModel().getRoot();
		        }
		        else
		        {
		            parentNode = (DefaultMutableTreeNode)(parentPath.getLastPathComponent());
		        }
		        
		        String childName=null;
		        
		        if(parentNode.getChildCount() > 0)
		        {
			        for(int k=0;k<parentNode.getChildCount();k++)
			        {
			        	childName = parentNode.getChildAt(k).toString();
			        	if(childName.equals(field.getText()))
			        	{
			        		breakChk = true;
			        		break;
			        	}
			        }
			        if(breakChk == false)
			       		treeModel.insertNodeInto(child, parentNode, parentNode.getChildCount());
			    }
			    else if(parentNode.getChildCount() == 0)
			    	treeModel.insertNodeInto(child, parentNode, parentNode.getChildCount());
		    	
		        
		        tree.expandRow(0);
		        tree.expandPath(parentPath);
		}
	}	
}