package com.sbs.jpm.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.ui.RootPanel;
import com.smartgwt.client.data.AdvancedCriteria;
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.rpc.RPCResponse;
import com.smartgwt.client.types.DSDataFormat;
import com.smartgwt.client.types.DSProtocol;
import com.smartgwt.client.types.FieldType;
import com.smartgwt.client.types.OperatorId;
import com.smartgwt.client.util.JSOHelper;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
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 Panel panel;
	private TestDataSource dataSource;

	public void onModuleLoad() {

		SC.showConsole();

		dataSource = new TestDataSource();

		panel = new Panel();
		panel.setWidth100();
		panel.setHeight100();

		RootPanel.get().add(panel);
	}

	public class Panel extends VLayout {

		private TreeGridField nameTreeGridField;
		private TreeGridField uidTreeGridField;
		private TreeGridField parentTreeGridField;
		private DynamicForm form;
		private SelectItem selectItem;
		
		private TreeGrid treeGrid;

		public Panel() {
			selectItem = new SelectItem();  
            selectItem.setOptionDataSource(dataSource);  
            selectItem.setDisplayField(TestDataSource.NAME_FIELD);  
            selectItem.setValueField(TestDataSource.UNIQUE_ID_FIELD);  
            selectItem.setPickListWidth(300);  
            selectItem.setTitle("Select");
            selectItem.addChangedHandler(new ChangedHandler() {
				@Override
				public void onChanged(ChangedEvent event) {
					String filterId = event.getValue().toString();
					SC.logWarn("---------"+filterId);
					AdvancedCriteria criteria = new AdvancedCriteria(TestDataSource.UNIQUE_ID_FIELD,
									OperatorId.EQUALS, filterId);
					treeGrid.setImplicitCriteria(criteria);
					treeGrid.fetchData();
				}
			});

			nameTreeGridField = new TreeGridField();
			nameTreeGridField.setName(TestDataSource.NAME_FIELD);
			nameTreeGridField.setTitle("Name");
			nameTreeGridField.setTreeField(true);
			
			uidTreeGridField = new TreeGridField();
			uidTreeGridField.setName(TestDataSource.UNIQUE_ID_FIELD);
			uidTreeGridField.setTitle("UID");

			parentTreeGridField = new TreeGridField();
			parentTreeGridField.setName(TestDataSource.PARENT_UNIQUE_ID);
			parentTreeGridField.setTitle("Parent");

			TextItem nameField = new TextItem();
			nameField.setTitle("Name");
			nameField.setName(TestDataSource.NAME_FIELD);

			treeGrid = new TreeGrid();
			treeGrid.setWidth(500);
			treeGrid.setHeight(500);
			treeGrid.setDataSource(dataSource);
			treeGrid.setTreeRootValue("root");
			treeGrid.setLoadDataOnDemand(false);
			
			treeGrid.setKeepParentsOnFilter(true);
			
			treeGrid.setFields(uidTreeGridField, nameTreeGridField);
			
			form = new DynamicForm();
			form.setWidth(500);
			form.setHeight(120);
			form.setIsGroup(true);
			form.setGroupTitle("Details");
			form.setDataSource(dataSource);
			form.setFields(selectItem);

			this.setMembers(form, treeGrid);
		}
	}

	
	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(TestDataSource.UNIQUE_ID_FIELD, value);
		}

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

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

	public class TestDataSource 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 TestDataSource() {

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

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

			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) {

			TaskTreeNode root = new TaskTreeNode("root", null, "All Projects");
			TaskTreeNode node2 = new TaskTreeNode("p1", "root", "Project 1");
			TaskTreeNode node3 = new TaskTreeNode("t1", "p1", "Task 1");
			TaskTreeNode node4 = new TaskTreeNode("t2", "p1", "Task 2");

			response.setData(new TreeNode[] { root, node2, node3, node4 });
			response.setStatus(RPCResponse.STATUS_SUCCESS);
			response.setInvalidateCache(true);
			processResponse(requestId, response);
		}

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

			final ListGridRecord editedRecord = getEditedRecord(request);
			response.setData(editedRecord);
			response.setStatus(RPCResponse.STATUS_SUCCESS);
			processResponse(requestId, response);
		}

		@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();
		}

		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;
	}
}
