package ibase.client;

import ibase.client.FilterInfo;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;

public class InputListWidget extends Composite
{
	List<String> itemsSelected = new ArrayList<String>();

	public InputListWidget(String suggetions, HorizontalPanel popUpHPnl, FilterInfo filterInfo, String[] splitedArray)
	{
		final BulletList list = new BulletList();
		list.setTitle(filterInfo.getColName());
		list.setStyleName("token-input-list");
		final ListItem item = new ListItem();
		item.setStyleName("token-input-input-token");
		final TextBox itemBox = new TextBox();
		itemBox.getElement().setAttribute("style", "outline-color: -moz-use-text-color; outline-style: none; outline-width: medium;");
		final SuggestBox box = new SuggestBox(getSuggestions(suggetions), itemBox);
		box.getElement().setId("suggestion_box");
		item.add(box);
		Paragraph paragraph = null;
		Span span = null;

		if (splitedArray != null)
		{
			for (int arrayCnt = 0; arrayCnt < splitedArray.length; arrayCnt++)
			{
				final ListItem onLodListItm = new ListItem();
				// onLodListItm.setStyleName("token-input-input-token");
				paragraph = new Paragraph();
				paragraph.setText(splitedArray[arrayCnt]);

				onLodListItm.setStyleName("token-input-token");

				onLodListItm.addClickHandler(new ClickHandler()
				{
					public void onClick(ClickEvent clickEvent)
					{
						onLodListItm.addStyleName("token-input-selected-token");
					}
				});

				span = new Span("x");
				span.addClickHandler(new ClickHandler()
				{
					public void onClick(ClickEvent clickEvent)
					{
						removeListItem(onLodListItm, list);
					}
				});
				onLodListItm.add(paragraph);
				onLodListItm.add(span);

				itemBox.setFocus(true);
				list.add(onLodListItm);
			}
		}
		list.add(item);
		itemBox.addKeyDownHandler(new KeyDownHandler()
		{
			public void onKeyDown(KeyDownEvent event)
			{
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER)
				{
					// only allow manual entries with @ signs (assumed email
					// addresses)
					if (itemBox.getValue().contains("@"))
						deselectItem(itemBox, list);
				}
				// handle backspace
				if (event.getNativeKeyCode() == KeyCodes.KEY_BACKSPACE)
				{
					if ("".equals(itemBox.getValue().trim()))
					{
						ListItem li = (ListItem) list.getWidget(list.getWidgetCount() - 2);
						Paragraph p = (Paragraph) li.getWidget(0);
						if (itemsSelected.contains(p.getText()))
						{
							itemsSelected.remove(p.getText());
							GWT.log("Removing selected item '" + p.getText() + "'", null);
							GWT.log("Remaining: " + itemsSelected, null);
						}
						list.remove(li);
						itemBox.setFocus(true);
					}
				}
			}
		});

		box.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>()
		{
			public void onSelection(SelectionEvent selectionEvent)
			{
				deselectItem(itemBox, list);
			}
		});

		popUpHPnl.add(list);
		popUpHPnl.getElement().setAttribute("onclick", "document.getElementById('suggestion_box').focus()");
		box.setFocus(true);
	}

	private void deselectItem(final TextBox itemBox, final BulletList list)
	{
		if (itemBox.getValue() != null && !"".equals(itemBox.getValue().trim()))
		{

			final ListItem displayItem = new ListItem();
			displayItem.setStyleName("token-input-token");
			Paragraph p = new Paragraph(itemBox.getValue());

			displayItem.addClickHandler(new ClickHandler()
			{
				public void onClick(ClickEvent clickEvent)
				{
					displayItem.addStyleName("token-input-selected-token");
				}
			});

			Span span = new Span("x");
			span.addClickHandler(new ClickHandler()
			{
				public void onClick(ClickEvent clickEvent)
				{
					removeListItem(displayItem, list);
				}
			});

			displayItem.add(p);
			displayItem.add(span);
			// hold the original value of the item selected

			GWT.log("Adding selected item '" + itemBox.getValue() + "'", null);
			itemsSelected.add(itemBox.getValue());
			GWT.log("Total: " + itemsSelected, null);

			list.insert(displayItem, list.getWidgetCount() - 1);
			itemBox.setValue("");
			itemBox.setFocus(true);
		}
	}

	private void removeListItem(ListItem displayItem, BulletList list)
	{
		GWT.log("Removing: " + displayItem.getWidget(0).getElement().getInnerHTML(), null);
		itemsSelected.remove(displayItem.getWidget(0).getElement().getInnerHTML());
		list.remove(displayItem);
	}

	public MultiWordSuggestOracle getSuggestions(String xmlMetadata)
	{
		MultiWordSuggestOracle oracle = new MultiWordSuggestOracle();
		NodeList rootNodeList = null;
		Document document = null;
		Node groupNode = null;
		NodeList headerList = null;
		Node headerNode = null;
		NodeList detalList = null;
		Node detailNode = null;
		NodeList columnList = null;
		Node columnNode = null;
		try
		{
			document = XMLParser.parse(xmlMetadata);
			if (document != null)
			{
				rootNodeList = document.getElementsByTagName("DOCUMENTROOT").item(0).getChildNodes();
				for (int rootCtr = 0; rootCtr < rootNodeList.getLength(); rootCtr++)
				{
					groupNode = rootNodeList.item(rootCtr);
					if ("GROUP0".equals(groupNode.getNodeName()))
					{
						headerList = groupNode.getChildNodes();
						for (int nodeCtr = 0; nodeCtr < headerList.getLength(); nodeCtr++)
						{
							headerNode = headerList.item(nodeCtr);
							if ("HEADER0".equals(headerNode.getNodeName()))
							{
								detalList = headerNode.getChildNodes();
								for (int headCtr = 0; headCtr < detalList.getLength(); headCtr++)
								{
									detailNode = detalList.item(headCtr);
									if ("DETAIL".equals(detailNode.getNodeName()))
									{
										columnList = detailNode.getChildNodes();
										for (int colNodCtr = 0; colNodCtr < 1; colNodCtr++)
										{
											columnNode = columnList.item(colNodCtr);
											oracle.add(columnNode.getChildNodes().item(0).getNodeValue());
										}
									}
								}
							}
						}
					}
				}
			}
		} catch (Exception e)
		{
			System.out.println(" Exception in  getparsing(String xmlMetadata)" + e.getMessage());
			e.printStackTrace();
		}
		/*
		 * oracle = new MultiWordSuggestOracle(); oracle.add("Amy Kesic");
		 * oracle.add("Jason Weston"); oracle.add("Dave Johnson");
		 * oracle.add("Paul Hammant"); oracle.add("Jesse Kuhnert");
		 * oracle.add("Ben Alex"); oracle.add("Tom Bender");
		 * oracle.add("Alexandru Popescu"); oracle.add("Kaveh Arabfakhry");
		 * oracle.add("Steven Hong"); oracle.add("Jason van Zyl");
		 * oracle.add("Alex Vauthey"); oracle.add("Kiran Karnati");
		 * oracle.add("Kalpana Nagireddy"); oracle.add("Ramnivas Laddad");
		 * oracle.add("Arj� Cahn"); oracle.add("Amy Anne Rasberry");
		 * oracle.add("Vincent Stoessel");
		 */
		return oracle;
	}
}
