/**
 * 
 */
package org.gcube.portlets.user.workspace.client.view.toolbars;

import java.util.LinkedHashMap;
import java.util.List;

import org.gcube.portlets.user.workspace.client.AppController;
import org.gcube.portlets.user.workspace.client.event.PathElementSelectedEvent;
import org.gcube.portlets.user.workspace.client.model.FileModel;

import com.github.gwtbootstrap.client.ui.NavLink;
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.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;

/**
 * 
 * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
 * @Jul 28, 2014
 * 
 */
public class Breadcrumbs extends Composite {

	/**
	 * 
	 */
	public static final String DIVIDER = ">";
	private String rootName;
	private LinkedHashMap<String, FileModel> hashFileModel = new LinkedHashMap<String, FileModel>();// Ordered-HashMap
	private FileModel lastParent;
	private static BreadcrumbsUiBinder uiBinder = GWT.create(BreadcrumbsUiBinder.class);

	@UiField
	com.github.gwtbootstrap.client.ui.Breadcrumbs breadcrumbs;

	interface BreadcrumbsUiBinder extends UiBinder<Widget, Breadcrumbs> {
	}

	public Breadcrumbs(String rootName) {
		this.rootName = rootName;
		initWidget(uiBinder.createAndBindUi(this));
		breadcrumbs.setDivider(DIVIDER);
		// initBreadcrumb(true);
		this.addStyleName("Breadcrumbs-Personal");
	}

	public void setPath(List<FileModel> parents) {

		resetBreadcrumbs();

		if (parents != null && parents.size() > 0) {

			hashFileModel = new LinkedHashMap<String, FileModel>();

			for (FileModel parent : parents) {
				addNavigationLink(parent);
				hashFileModel.put(parent.getIdentifier(), parent);
			}

			lastParent = parents.get(parents.size() - 1);
		}
	}



	private void resetBreadcrumbs() {
		breadcrumbs.clear();
	}

	// @UiHandler("add")
	public void addNavigationLink(FileModel parent) {
		if (! parent.isRoot()) {
			final NavLink navLink = new NavLink(parent.getName());
			navLink.setName(parent.getIdentifier());
			breadcrumbs.add(navLink);

			navLink.addClickHandler(new ClickHandler() {

				@Override
				public void onClick(ClickEvent event) {

					FileModel target = hashFileModel.get(navLink.getName());
					AppController.getEventBus().fireEvent(
							new PathElementSelectedEvent(target));

				}
			});
		} else {
			final NavLink navLink = new NavLink("");
			breadcrumbs.add(navLink);
		}
	}

	public boolean breadcrumbIsEmpty() {

		if (hashFileModel.size() == 0)
			return true;

		return false;
	}

	public FileModel getLastParent() {
		return lastParent;
	}

}