package org.gcube.portlets.user.td.client;

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

import org.gcube.portlets.user.td.client.grid.GridHeaderColumnMenu;
import org.gcube.portlets.user.td.client.grid.GridContextMenu;
import org.gcube.portlets.user.td.client.ribbon.TabularDataRibbon;
import org.gcube.portlets.user.td.client.rpc.TabularDataService;
import org.gcube.portlets.user.td.client.rpc.TabularDataServiceAsync;
import org.gcube.portlets.user.td.toolboxwidget.client.ToolBoxPanel;
import org.gcube.portlets.user.td.widgetcommonevent.shared.GridHeaderOperationId;
import org.gcube.portlets.user.tdwx.client.TabularDataX;
import org.gcube.portlets.user.tdwx.client.TabularDataXGridPanel;
import org.gcube.portlets.user.tdwx.client.config.Row;
import org.gcube.portlets.user.tdwx.client.event.FailureEvent;
import org.gcube.portlets.user.tdwx.client.event.FailureEventHandler;
import org.gcube.portlets.user.tdwx.client.model.grid.DataRowColumnConfig;
import org.gcube.portlets.user.tdwx.shared.model.DataRow;



import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.web.bindery.event.shared.EventBus;
import com.sencha.gxt.core.client.Style.SelectionMode;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.widget.core.client.TabPanel;
import com.sencha.gxt.widget.core.client.box.AlertMessageBox;
import com.sencha.gxt.widget.core.client.container.BorderLayoutContainer;
import com.sencha.gxt.widget.core.client.container.BorderLayoutContainer.BorderLayoutData;
import com.sencha.gxt.widget.core.client.container.MarginData;
import com.sencha.gxt.widget.core.client.container.Viewport;
import com.sencha.gxt.widget.core.client.event.HideEvent;
import com.sencha.gxt.widget.core.client.event.HideEvent.HideHandler;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.info.Info;
import com.sencha.gxt.widget.core.client.menu.Item;
import com.sencha.gxt.widget.core.client.menu.Menu;
import com.sencha.gxt.widget.core.client.menu.MenuItem;

/**
 * 
 * @author "Giancarlo Panichi" <a
 *         href="mailto:g.panichi@isti.cnr.it">g.panichi@isti.cnr.it</a>
 * 
 */
public class TabularDataPortlet implements EntryPoint {

	protected static final String JSP_TAG_ID = "tdp";

	/**
	 * 
	 */
	public static final int TOOLBOX_WIDTH = 300;
	/**
	 * 
	 */
	public static final int TOOLBOX_HEIGHT = 800;

	/**
	 * Create a remote service proxy to talk to the server-side Greeting
	 * service.
	 */
	@SuppressWarnings("unused")
	private final TabularDataServiceAsync greetingService = GWT
			.create(TabularDataService.class);

	// Main Panel
	private static BorderLayoutContainer mainPanelLayout;

	// Private TabularData
	private static TabularDataX tabularData;
	private static ToolBoxPanel toolBoxPanel;
	private static BorderLayoutData westData;

	/**
	 * {@inheritDoc}
	 */
	public void onModuleLoad() {

		/*
		 * Install an UncaughtExceptionHandler which will produce
		 * <code>FATAL</code> log messages
		 */
		Log.setUncaughtExceptionHandler();

		// use deferred command to catch initialization exceptions in
		// onModuleLoad2
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {
			public void execute() {
				loadMainPanel();
			}
		});

	}

	protected void loadMainPanel() {

		TabularDataController controller = new TabularDataController();
		EventBus eventBus = controller.getEventBus();

		tabularData = new TabularDataX(Constants.TDX_DATASOURCE_FACTORY_ID);
		tabularData.addFailureHandler(new FailureEventHandler() {

			
			public void onFailure(FailureEvent event) {
				Info.display("Error: " + event.getMessage(), event.getCaught()
						.getMessage());

			}
		});

		controller.setTabularData(tabularData);

		// Layout
		mainPanelLayout = new BorderLayoutContainer();
		mainPanelLayout.setId("mainPanelLayout");
		mainPanelLayout.setBorders(true);

		// Ribbon Menu
		TabularDataRibbon tabularDataTooBar = new TabularDataRibbon(eventBus);
		TabPanel toolBarPanel = tabularDataTooBar.getContainer();

		BorderLayoutData toolBarData = new BorderLayoutData(111);
		toolBarData.setMargins(new Margins(5));
		toolBarData.setCollapsible(false);
		toolBarData.setSplit(false);

		mainPanelLayout.setNorthWidget(toolBarPanel, toolBarData);

		// Grid Panel
		final TabularDataXGridPanel gridPanel = tabularData.getGridPanel();
		gridPanel.setHeaderVisible(false);
		
		GridHeaderColumnMenu columnHeaderMenu=new GridHeaderColumnMenu();
		gridPanel.addGridHeaderContextMenuItems(columnHeaderMenu.getMenu(), eventBus);
		
		GridContextMenu gridContextMenu=new GridContextMenu();
		gridPanel.setGridContextMenu(gridContextMenu.getMenu());
		
		MarginData gridData = new MarginData();
		mainPanelLayout.setCenterWidget(gridPanel, gridData);

		// ToolBox Panel
		toolBoxPanel = new ToolBoxPanel("ToolBoxPanel",eventBus);
		
	
		westData = new BorderLayoutData(310);
		westData.setCollapsible(true);
		westData.setSplit(false);
		westData.setFloatable(false);
		westData.setCollapseMini(true);
		westData.setMargins(new Margins(0, 5, 0, 5));
		westData.setCollapseHidden(true);

		mainPanelLayout.setWestWidget(toolBoxPanel, westData);
		toolBoxPanel.collapse();
		toolBoxPanel.disable();

		
		controller.setToolBoxPanel(toolBoxPanel);
		controller.setEastData(westData);

		bind(mainPanelLayout);
		//menu(gridPanel);
		
	}

	protected void bind(BorderLayoutContainer mainWidget) {
		try {
			RootPanel root = RootPanel.get(JSP_TAG_ID);
			Log.info("Root Panel: " + root);
			if (root == null) {
				Log.info("Div with id " + JSP_TAG_ID
						+ " not found, starting in dev mode");
				Viewport viewport = new Viewport();
				viewport.setWidget(mainWidget);
				viewport.onResize();
				RootPanel.get().add(viewport);
			} else {
				Log.info("Application div with id " + JSP_TAG_ID
						+ " found, starting in portal mode");
				PortalViewport viewport = new PortalViewport();
				Log.info("Created Viewport");
				viewport.setEnableScroll(false);
				viewport.setWidget(mainWidget);
				Log.info("Set Widget");
				Log.info("getOffsetWidth(): " + viewport.getOffsetWidth());
				Log.info("getOffsetHeight(): " + viewport.getOffsetHeight());
				viewport.onResize();
				root.add(viewport);
				Log.info("Added viewport to root");
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.error("Error in attach viewport:" + e.getLocalizedMessage());
		}
	}
    /*
	protected void menu(final TabularDataXGridPanel gridPanel) {
		Log.debug("Add Menu to tabular data widget");
		final HideHandler hideHandler = new HideHandler() {

			@Override
			public void onHide(HideEvent event) {
				// TODO Auto-generated method stub

			}
		};
		Log.debug("Set SelectionMode.SINGLE");
		gridPanel.setSelectionModel(SelectionMode.SINGLE);
		Log.debug("Init menu creation");
		Menu menu = new Menu();
		Log.debug("Create Item");
		MenuItem item = new MenuItem("Selected");
		Log.debug("Added Handler");

		item.addSelectionHandler(new SelectionHandler<Item>() {
			@Override
			public void onSelection(SelectionEvent<Item> event) {
				Log.debug("Start On Selection");
				Log.debug("gridPanel is: " + gridPanel);
				if (gridPanel != null) {
					ColumnModel<DataRow> columnModel = gridPanel.getGrid()
							.getColumnModel();

					List<ColumnConfig<DataRow, ?>> columns = columnModel
							.getColumns();
					for (ColumnConfig<DataRow, ?> cc : columns) {
						Log.debug("ColumnConfig:" + cc.getHeader());
					}

					DataRowColumnConfig<?> dc = (DataRowColumnConfig<?>) columns
							.get(0);

					Log.debug("DC - Header:" + dc.getHeader());
					Log.debug("DC - Definition:" + dc.getDefinition().getId()
							+ " Label:" + dc.getDefinition().getLabel()
							+ " Key:" + dc.getDefinition().getKey());

					Row row = gridPanel.getSelectedRow();
					Log.debug("Retrived row");

					String rowInfo;
					if (row != null) {
						rowInfo = row.getFieldAsText(dc.getDefinition()
								.getLabel());
					} else {
						rowInfo = "no row retrived";
					}
					Log.debug("Set Alert");
					AlertMessageBox d = new AlertMessageBox("Selected",
							"Row: \n" + rowInfo);
					d.addHideHandler(hideHandler);
					d.show();
				}
			}
		});
		Log.debug("Add Item to Menu");
		menu.add(item);
		Log.debug("Set Menu on Tabular data Widget");
		gridPanel.setContextMenu(menu);
	}

	*/

	/*
	 * private void configPanel(final Portlet panel) {
	 * panel.setCollapsible(true); panel.setAnimCollapse(false);
	 * //panel.getHeader().addTool(new ToolButton(ToolButton.GEAR));
	 * panel.getHeader().addTool(new ToolButton(ToolButton.CLOSE));
	 * 
	 * }
	 */
	
	
	

}
