package com.sbs.jpm.client;

import java.util.Date;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.RootPanel;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.types.DSDataFormat;
import com.smartgwt.client.types.DSOperationType;
import com.smartgwt.client.types.DSProtocol;
import com.smartgwt.client.types.FieldType;
import com.smartgwt.client.util.JSOHelper;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.tree.TreeGrid;
import com.smartgwt.client.widgets.tree.TreeGridField;
import com.smartgwt.client.widgets.tree.TreeNode;

public class TestCase implements EntryPoint {

	private WBSPanel wbsPanel;
	private TaskDataSource dataSource;

	public void onModuleLoad() {

		dataSource = new TaskDataSource();

		wbsPanel = new WBSPanel();
		wbsPanel.setWidth100();
		wbsPanel.setHeight100();

		RootPanel.get().add(wbsPanel);

	}

	public class WBSPanel extends VLayout {

		private Button addToolbarButton;

		private TreeGrid tasksTreeGrid;
		private TreeGridField nameTreeGridField;

		public WBSPanel() {

			addToolbarButton = new Button();
			addToolbarButton.setTitle("Add");
			addToolbarButton.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					addTask();
				}
			});

			nameTreeGridField = new TreeGridField();
			nameTreeGridField.setName(TaskDataSource.NAME_FIELD);
			nameTreeGridField.setTitle("Task Name");
			nameTreeGridField.setTreeField(true);

			tasksTreeGrid = new TreeGrid();
			tasksTreeGrid.setWidth100();
			tasksTreeGrid.setHeight100();
			tasksTreeGrid.setDataSource(dataSource);
			tasksTreeGrid.setLoadDataOnDemand(false);
			tasksTreeGrid.fetchData();
			tasksTreeGrid.setFields(nameTreeGridField);

			this.setMembers(addToolbarButton, tasksTreeGrid);
		}

		private void addTask() {

			// when we add this record into a hierarchical structure, if a
			// component that shows a filtered set of data but doesn't shows the
			// parent of this added record will not get redrawn on updateCache
			// (will not show this record even if this record exists in the
			// datasource cache).
			// If you replace the value of PARENT_UNIQUE_ID which now is 1 in
			// order to reproduce the bug with 4 in this case then all will work
			// as expected
			Record newTaskt = new Record();
			newTaskt.setAttribute(TaskDataSource.NAME_FIELD, "New task");
			newTaskt.setAttribute(TaskDataSource.PARENT_UNIQUE_ID, 1);
			newTaskt.setAttribute(TaskDataSource.UNIQUE_ID_FIELD,
					new Date().getTime());

			tasksTreeGrid.addData(newTaskt);
		}
	}

	public class TaskTreeNode extends TreeNode {

		public TaskTreeNode(String taskId, String reportsTo, String name) {
			setTaskId(taskId);
			setReportsTo(reportsTo);
			setName(name);
		}

		public void setTaskId(String value) {
			setAttribute(TaskDataSource.UNIQUE_ID_FIELD, value);
		}

		public void setReportsTo(String value) {
			setAttribute(TaskDataSource.PARENT_UNIQUE_ID, value);
		}

		public void setName(String name) {
			setAttribute(TaskDataSource.NAME_FIELD, name);
		}
	}

	public class TaskDataSource extends GwtRpcDataSource {
		private static final String DS_UNIQUE_ID = "_TaskDataSource";

		public static final String PARENT_UNIQUE_ID = "parentUniqueId"
				+ DS_UNIQUE_ID;
		public static final String UNIQUE_ID_FIELD = "uniqueIdField"
				+ DS_UNIQUE_ID;
		public static final String NAME_FIELD = "nameField" + DS_UNIQUE_ID;

		private TaskDataSource() {

			DataSourceField uniqueId = new DataSourceField();
			uniqueId.setName(UNIQUE_ID_FIELD);
			uniqueId.setPrimaryKey(true);
			uniqueId.setHidden(true);
			uniqueId.setType(FieldType.INTEGER);

			DataSourceField reportsToField = new DataSourceField();
			reportsToField.setName(PARENT_UNIQUE_ID);
			reportsToField.setForeignKey(DS_UNIQUE_ID + "." + UNIQUE_ID_FIELD);
			reportsToField.setHidden(true);
			reportsToField.setType(FieldType.INTEGER);

			this.setID(DS_UNIQUE_ID);
			this.setFields(uniqueId, reportsToField);
			this.setCacheAllData(true);
			this.setCacheMaxAge(3600);
		}

		@Override
		protected void executeFetch(final String requestId, DSRequest request,
				final DSResponse response) {

			Timer timer = new Timer() {
				@Override
				public void run() {
					TaskTreeNode root = new TaskTreeNode("4", "1",
							"Charles Madigen");
					TaskTreeNode node2 = new TaskTreeNode("188", "1",
							"Rogine Leger");
					TaskTreeNode node3 = new TaskTreeNode("189", "1",
							"Gene Porter");
					TaskTreeNode node4 = new TaskTreeNode("265", "1",
							"Olivier Doucet");
					TaskTreeNode node5 = new TaskTreeNode("264", "1",
							"Cheryl Pearson");

					response.setData(new TreeNode[] { root, node2, node3,
							node4, node5 });
					response.setStatus(RPCResponse.STATUS_SUCCESS);
					response.setInvalidateCache(true);
					processResponse(requestId, response);
				}
			};
			// timer to simulate the response delay from the server
			// also noticed that if setCacheAllData is true the components don't
			// received fetch data so this is also a workaround. it also works
			// with
			// schedule(0)
			timer.schedule(1000);
		}

		@Override
		protected void executeAdd(final String requestId, DSRequest request,
				final DSResponse response) {

			// simulate the add record on the server. On response I call
			// updateCaches to update all the components data and to show the
			// bug
			final ListGridRecord editedRecord = getEditedRecord(request);

			Timer timer = new Timer() {
				@Override
				public void run() {
					DSResponse rsp = new DSResponse();
					rsp.setData(editedRecord);
					rsp.setOperationType(DSOperationType.ADD);
					updateCaches(rsp);
				}
			};
			timer.schedule(1000);
		}

		@Override
		protected void executeUpdate(final String requestId,
				final DSRequest request, final DSResponse response) {
		}

		@Override
		protected void executeRemove(final String requestId, DSRequest request,
				final DSResponse response) {
		}
	}

	public abstract class GwtRpcDataSource extends DataSource {

		public GwtRpcDataSource() {
			setDataProtocol(DSProtocol.CLIENTCUSTOM);
			setDataFormat(DSDataFormat.CUSTOM);
			setClientOnly(false);
		}

		@Override
		protected Object transformRequest(DSRequest request) {
			String requestId = request.getRequestId();
			DSResponse response = new DSResponse();
			response.setAttribute("clientContext",
					request.getAttributeAsObject("clientContext"));
			response.setStatus(0);

			switch (request.getOperationType()) {
			case FETCH:
				executeFetch(requestId, request, response);
				break;
			case ADD:
				executeAdd(requestId, request, response);
				break;
			case UPDATE:
				executeUpdate(requestId, request, response);
				break;
			case REMOVE:
				executeRemove(requestId, request, response);
				break;
			default:
				break;
			}
			return request.getData();
		}

		@Override
		public void processResponse(String requestId,
				DSResponse responseProperties) {
			super.processResponse(requestId, responseProperties);
		}

		protected abstract void executeFetch(String requestId,
				DSRequest request, DSResponse response);

		protected abstract void executeAdd(String requestId, DSRequest request,
				DSResponse response);

		protected abstract void executeUpdate(String requestId,
				DSRequest request, DSResponse response);

		protected abstract void executeRemove(String requestId,
				DSRequest request, DSResponse response);

	}

	protected ListGridRecord getEditedRecord(DSRequest request) {
		ListGridRecord newRecord = new ListGridRecord();
		newRecord = getOldRecord(request);
		JavaScriptObject data = request.getData();
		JSOHelper.apply(data, newRecord.getJsObj());
		return newRecord;
	}

	protected ListGridRecord getOldRecord(DSRequest request) {
		JavaScriptObject oldValues = request
				.getAttributeAsJavaScriptObject("oldValues");
		ListGridRecord oldRecord = new ListGridRecord();
		JSOHelper.apply(oldValues, oldRecord.getJsObj());
		return oldRecord;
	}
}
