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

import org.gcube.portlets.user.td.csvexportwidget.client.CSVExportWizardTD;
import org.gcube.portlets.user.td.csvimportwidget.client.CSVImportWizardTD;
import org.gcube.portlets.user.td.gwtservice.client.rpc.TDGWTServiceAsync;
import org.gcube.portlets.user.td.openwidget.client.TDOpen;
import org.gcube.portlets.user.td.sdmxexportwidget.client.SDMXExportWizardTD;
import org.gcube.portlets.user.td.sdmximportwidget.client.SDMXImportWizardTD;
import org.gcube.portlets.user.td.taskswidget.client.TdTaskController;
import org.gcube.portlets.user.td.widgetcommonevent.client.event.GridHeaderColumnMenuItemEvent;
import org.gcube.portlets.user.td.widgetcommonevent.client.event.RibbonEvent;
import org.gcube.portlets.user.td.widgetcommonevent.client.event.UIStateEvent;
import org.gcube.portlets.user.td.widgetcommonevent.client.type.RibbonType;
import org.gcube.portlets.user.td.widgetcommonevent.client.type.UIStateType;
import org.gcube.portlets.user.td.widgetcommonevent.shared.GridHeaderOperationId;
import org.gcube.portlets.user.td.widgetcommonevent.shared.TRId;
import org.gcube.portlets.user.td.wizardwidget.client.WizardListener;
import org.gcube.portlets.user.tdwx.client.TabularDataX;
import org.gcube.portlets.user.tdwx.shared.model.TableId;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.dom.client.Document;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.sencha.gxt.core.client.Style.Anchor;
import com.sencha.gxt.core.client.Style.AnchorAlignment;
import com.sencha.gxt.core.client.util.Point;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.box.AlertMessageBox;
import com.sencha.gxt.widget.core.client.container.BorderLayoutContainer.BorderLayoutData;
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.info.Info;

/**
 * 
 * @author "Giancarlo Panichi" <a
 *         href="mailto:g.panichi@isti.cnr.it">g.panichi@isti.cnr.it</a>
 * 
 */
public class TabularDataController {
	// implements HasCloseHandlers<Long>, HasOpenHandlers<Long> {

	protected SimpleEventBus eventBus;
	protected TabularDataX tabularData;
	protected UIStateType uiState = UIStateType.START;

	protected ContentPanel toolBoxPanel;
	protected BorderLayoutData eastData;

	/**
	 * Tabular Resource Id
	 */
	protected TRId trId;

	/**
	 * Grid TableId
	 */
	protected TableId tableOpening;

	public TabularDataController() {
		eventBus = new SimpleEventBus();
		bindToEvents();
	}

	/**
	 * @return the eventBus
	 */
	public EventBus getEventBus() {
		return eventBus;
	}

	public void setTabularData(TabularDataX tabularData) {
		this.tabularData = tabularData;
	}

	public ContentPanel getToolBoxPanel() {
		return toolBoxPanel;
	}

	public void setToolBoxPanel(ContentPanel toolBoxPanel) {
		this.toolBoxPanel = toolBoxPanel;
	}

	public BorderLayoutData getEastData() {
		return eastData;
	}

	public void setEastData(BorderLayoutData eastData) {
		this.eastData = eastData;
	}

	protected void bindToEvents() {
		eventBus.addHandler(
				GridHeaderColumnMenuItemEvent.TYPE,
				new GridHeaderColumnMenuItemEvent.GridHeaderColumnMenuItemEventHandler() {

					public void onGridHeaderColumnMenuItemEvent(
							GridHeaderColumnMenuItemEvent event) {
						Log.debug("Catch Event HeaderColumnMenuItemEvent");
						doGridHeaderColumnMenuCommand(event);

					}
				});

		eventBus.addHandler(RibbonEvent.TYPE,
				new RibbonEvent.RibbonEventHandler() {

					public void onRibbon(RibbonEvent event) {
						doRibbonCommand(event);

					}
				});

		eventBus.fireEvent(new UIStateEvent(UIStateType.START));

	}

	protected void alertMessage(String reason, String details) {
		AlertMessageBox d = new AlertMessageBox(reason, details);
		d.addHideHandler(new HideHandler() {

			public void onHide(HideEvent event) {
				//
			}

		});
		d.show();
	}

	protected void resumeUIState() {
		if (uiState == UIStateType.TR_OPEN) {
			UIStateEvent uiStateEvent = new UIStateEvent(UIStateType.TR_OPEN);
			uiStateEvent.setTrId(trId);
			eventBus.fireEvent(uiStateEvent);
		} else {
			eventBus.fireEvent(new UIStateEvent(UIStateType.TR_CLOSE));
		}
	}

	protected void openTable(TRId tabularResourceId) {
		Log.debug("openTabe: " + tabularResourceId);
		trId = tabularResourceId;
		tableOpening = new TableId(Constants.TDX_DATASOURCE_FACTORY_ID,
				trId.getTableId());
		tabularData.openTable(tableOpening);
		uiState = UIStateType.TR_OPEN;
		UIStateEvent uiStateEvent = new UIStateEvent(UIStateType.TR_OPEN);
		uiStateEvent.setTrId(tabularResourceId);
		eventBus.fireEvent(uiStateEvent);
	}

	/*
	 * protected void updateUIProperties(){ if (uiToolBox == UIToolBox.OPENED) {
	 * trProperties.update(); } }
	 */

	protected void closeTabularResource() {
		if (uiState == UIStateType.TR_OPEN) {
			tabularData.closeTable();
			uiState = UIStateType.TR_CLOSE;
			eventBus.fireEvent(new UIStateEvent(UIStateType.TR_CLOSE));

		}
	}

	protected void deleteTabularResource() {
		Log.debug("Remove TR:" + trId);
		TDGWTServiceAsync.INSTANCE.removeTabularResource(trId,
				new AsyncCallback<Void>() {

					public void onFailure(Throwable caught) {
						alertMessage("Error", "Error on remove TabResource: "
								+ caught.getLocalizedMessage());
					}

					public void onSuccess(Void result) {
						closeTabularResource();
					}

				});

	}

	protected void openWizard() {
		eventBus.fireEvent(new UIStateEvent(UIStateType.WIZARD_OPEN));
	}

	public void doRibbonCommand(RibbonEvent event) {
		RibbonType type = event.getRibbonType();
		Log.trace("doRibbonEvent ribbonType: " + type);
		try {
			switch (type) {
			case OPEN:
				openTabularResource();
				break;
			case CLOSE:
				closeTabularResource();
				break;
			case DELETE:
				deleteTabularResource();
				break;
			case PROPERTIES:
				break;
			case IMPORTSDMX:
				openSDMXImportWizard();
				break;
			case IMPORTCSV:
				openCSVImportWizard();
				break;
			case IMPORTJSON:
				break;
			case EXPORTSDMX:
				openSDMXExportWizard();
				break;
			case EXPORTCSV:
				openCSVExportWizard();
				break;
			case EXPORTJSON:
				break;
			case TASKSMANAGER:
				openTasksManagerWizard();
				break;
			default:
				break;
			}
		} catch (Exception e) {
			Log.error("doRibbonCommand Error : " + e.getLocalizedMessage()
					+ " \n " + e.getMessage());
		}
	}

	/*
	 * protected void openToolBox() { if (uiState == UIStateType.TR_OPEN) { if
	 * (uiToolBox == UIToolBox.OPENED) { toolBoxPanel.collapse();
	 * toolBoxPanel.disable();
	 * 
	 * uiToolBox = UIToolBox.CLOSED; eventBus.fireEvent(new
	 * UIStateEvent(UIStateType.TOOLBOX_CLOSE)); toolBox.remove(trProperties);
	 * Info.display("Properties", "Closed"); } else { eventBus.fireEvent(new
	 * UIStateEvent(UIStateType.TOOLBOX_OPEN)); toolBoxPanel.enable();
	 * toolBoxPanel.expand(); uiToolBox = UIToolBox.OPENED;
	 * 
	 * } } else { Info.display("Properties", "No table open"); } };
	 */

	protected void openSDMXImportWizard() {
		GWT.runAsync(new RunAsyncCallback() {

			public void onSuccess() {
				openWizard();
				SDMXImportWizardTD importWizard = new SDMXImportWizardTD(
						"SDMX Import");
				importWizard.addListener(new WizardListener() {

					public void completed(TRId tabularResourceId) {
						openTable(tabularResourceId);
					}

					public void aborted() {
						resumeUIState();
					}

					public void failed(Throwable throwable, String reason,
							String details) {
						alertMessage(reason, details);
						resumeUIState();
					}

				});

				importWizard.show();
			}

			public void onFailure(Throwable reason) {
				asyncCodeLoadingFailed(reason);
			}
		});

	}

	protected void openCSVExportWizard() {
		GWT.runAsync(new RunAsyncCallback() {

			public void onSuccess() {
				openWizard();
				CSVExportWizardTD exportWizard = new CSVExportWizardTD(
						"CSV Export");

				exportWizard.addListener(new WizardListener() {
					public void failed(Throwable throwable, String reason,
							String details) {
						alertMessage(reason, details);
						resumeUIState();
					}

					public void completed(TRId id) {
						resumeUIState();

					}

					public void aborted() {
						resumeUIState();
					}
				});

				exportWizard.show();
			}

			public void onFailure(Throwable reason) {
				asyncCodeLoadingFailed(reason);
			}
		});

	}

	protected void openSDMXExportWizard() {
		GWT.runAsync(new RunAsyncCallback() {

			public void onSuccess() {
				openWizard();
				SDMXExportWizardTD exportWizard = new SDMXExportWizardTD(
						"SDMX Export");

				exportWizard.addListener(new WizardListener() {
					public void failed(Throwable throwable, String reason,
							String details) {
						alertMessage(reason, details);
						resumeUIState();
					}

					public void completed(TRId id) {
						resumeUIState();

					}

					public void aborted() {
						resumeUIState();
					}
				});

				exportWizard.show();
			}

			public void onFailure(Throwable reason) {
				asyncCodeLoadingFailed(reason);
			}
		});

	}

	/**
	 * 
	 */
	protected void openTabularResource() {
		Log.info("Open Tabular Resources");

		GWT.runAsync(new RunAsyncCallback() {

			public void onSuccess() {
				openWizard();
				TDOpen tdOpen = new TDOpen("Open Tabular Resource");

				tdOpen.addListener(new WizardListener() {

					public void aborted() {
						resumeUIState();
					}

					public void failed(Throwable throwable, String reason,
							String details) {
						alertMessage(reason, details);
						resumeUIState();
					}

					public void completed(TRId tabularResourceId) {
						openTable(tabularResourceId);

					}

				});
				Log.info("TDOpen add Listener");
				tdOpen.show();
			}

			public void onFailure(Throwable reason) {
				asyncCodeLoadingFailed(reason);
			}
		});

	}

	protected void openCSVImportWizard() {
		GWT.runAsync(new RunAsyncCallback() {

			public void onSuccess() {
				openWizard();
				CSVImportWizardTD importWizard = new CSVImportWizardTD(
						"CSV Import");

				importWizard.addListener(new WizardListener() {

					public void failed(Throwable throwable, String reason,
							String details) {
						alertMessage(reason, details);
						resumeUIState();
					}

					public void completed(TRId id) {
						openTable(id);

					}

					public void aborted() {
						resumeUIState();
					}
				});

				importWizard.show();
			}

			public void onFailure(Throwable reason) {
				asyncCodeLoadingFailed(reason);
			}
		});

	}

	protected TdTaskController tdTaskController;
	protected DialogBox tdTaskMainWindow;

	protected void openTasksManagerWizard() {

		tdTaskController = TdTaskController.getInstance();
		TdTaskController.bindCommonBus(eventBus);
		tdTaskMainWindow = tdTaskController.getWindowTaskMonitor(); 
		
		tdTaskMainWindow.setPopupPosition( (Window.getClientWidth()/2)-200, (Window.getClientHeight()/2)-300);
				 
		tdTaskMainWindow.show();

	}

	protected void doGridHeaderColumnMenuCommand(
			GridHeaderColumnMenuItemEvent event) {
		Log.debug("GridHeaderColumnMenu Fire Event",
				"OperationId: " + event.getOperationId() + " Column: \n"
						+ event.getColumnSelected());
		String opId = event.getOperationId();
		if (opId.compareTo(GridHeaderOperationId.AddLabel.toString()) == 0) {

		} else {
			if (opId.compareTo(GridHeaderOperationId.ChangeLabel.toString()) == 0) {

			} else {
				if (opId.compareTo(GridHeaderOperationId.RemoveLabel.toString()) == 0) {

				} else {
					if (opId.compareTo(GridHeaderOperationId.RemoveColumn
							.toString()) == 0) {

					} else {
						if (opId.compareTo(GridHeaderOperationId.ChangeToType
								.toString()) == 0) {

						} else {
							if (opId.compareTo(GridHeaderOperationId.ColumnDuplicateValidation
									.toString()) == 0) {

							} else {
								if (opId.compareTo(GridHeaderOperationId.Filter
										.toString()) == 0) {

								} else {
									if (opId.compareTo(GridHeaderOperationId.ModifyColumnValueOnCondition
											.toString()) == 0) {

									} else {
										if (opId.compareTo(GridHeaderOperationId.NewAnnotationColumn
												.toString()) == 0) {

										} else {

										}

									}

								}

							}

						}

					}
				}

			}

		}

	}

	protected void asyncCodeLoadingFailed(Throwable reason) {
		Log.error("Async code loading failed", reason);
		Info.display("Async code loading failed",
				"Please retry to lunch the operation");
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @Override public HandlerRegistration addCloseHandler(CloseHandler<Long>
	 *           handler) { //return eventBus.addHandler(CloseEvent.getType(),
	 *           handler); }
	 * 
	 *           /** {@inheritDoc}
	 * @Override public HandlerRegistration addOpenHandler(OpenHandler<Long>
	 *           handler) { //return eventBus.addHandler(OpenEvent.getType(),
	 *           handler); }
	 */

	/**
	 * {@inheritDoc}
	 * 
	 * @Override public void fireEvent(GwtEvent<?> event) {
	 *           eventBus.fireEvent(event); }
	 */

}
