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)
	{
		String[] itmBoxArr = null;
		String itmBoxValue = "";
		if (itemBox.getValue() != null && !"".equals(itemBox.getValue().trim()))
		{

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

			//**Added new code by sachin on 20/11/14*//

			itmBoxValue = itemBox.getValue();
			itmBoxArr = itmBoxValue.split("-");
			System.out.println(" spltedVlaue=" + itmBoxArr[0]);

			/** End Added new code by sachin on 20/11/14 */
			Paragraph p = new Paragraph(itmBoxArr[1].trim());
			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;
		String code = "";
		String descr = "";
		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 < 2; colNodCtr++)
										{
											columnNode = columnList.item(colNodCtr);
											if (colNodCtr == 0)
											{
												code = columnNode.getChildNodes().item(0).getNodeValue();
											} else if (colNodCtr == 1)
											{
												descr = columnNode.getChildNodes().item(0).getNodeValue();
											}
											//oracle.add(columnNode.getChildNodes().item(0).getNodeValue());
										}
										oracle.add(descr + " - " + code);
									}
								}
							}
						}
					}
				}
			}
		} catch (Exception e)
		{
			System.out.println(" Exception in  getparsing(String xmlMetadata)" + e.getMessage());
			e.printStackTrace();
		}

		return oracle;
	}
}
