package com.pci.sample.gridspeedtest.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.smartgwt.client.types.AnimationAcceleration;
import com.smartgwt.client.types.EnterKeyEditAction;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;

public class TestEntryPoint implements EntryPoint
{
	@Override
	public void onModuleLoad()
	{

		ListGrid grid = new ListGrid();
		grid.setWidth100();
		grid.setHeight100();
		grid.setCanResizeFields(true);
		grid.setVirtualScrolling(false);
		grid.setAnimateAcceleration(AnimationAcceleration.NONE);
		grid.setAnimateMembers(false);
		grid.setSmoothFade(false);
		grid.setFixedRecordHeights(true);
		grid.setAutoSaveEdits(false);
		grid.setEditByCell(true);
		grid.setCanSelectCells(true);
		grid.setSelectionType(SelectionStyle.MULTIPLE);
		grid.setCanDragSelect(true);
		grid.setEnterKeyEditAction(EnterKeyEditAction.NEXTROW);
		grid.setShowAllRecords(true);
		grid.setScrollRedrawDelay(0);
		grid.setScrollWheelRedrawDelay(0);

		try
		{
			new RequestBuilder(RequestBuilder.GET, "speedtest/fields.json").sendRequest("", new RequestCallback()
			{
				@Override
				public void onResponseReceived(Request request, Response response)
				{
					//Get fields JSON
					String fieldsJson = response.getText();
					try
					{
						new RequestBuilder(RequestBuilder.GET, "speedtest/data.json").sendRequest("", new RequestCallback()
						{
							@Override
							public void onResponseReceived(Request request, Response response)
							{
								//get Data JSON
								String dataJson = response.getText();

								setFields(grid, fieldsJson);
								setData(grid, dataJson);

								grid.draw();
							}

							@Override
							public void onError(Request request, Throwable exception)
							{
								System.out.println(exception.getMessage());
							}
						});
					}
					catch (RequestException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				@Override
				public void onError(Request request, Throwable exception)
				{
					System.out.println(exception.getMessage());
				}
			});
		}
		catch (RequestException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private static void setFields(final ListGrid grid, String fieldsJSON)
	{
		// Fields obtained through SmartGWT Console, using this expression:
		// JSON.stringify(DataSource.get("a_valid_data_source_name")['fields'])
		JavaScriptObject[] fieldArray = toArray(JsonUtils.unsafeEval(fieldsJSON));
		ListGridField[] fields = new ListGridField[fieldArray.length];
		for (int r = 0; r < fieldArray.length; r++)
		{
			fields[r] = new ListGridField(fieldArray[r]);
		}
		grid.setFields(fields);
	}

	private static void setData(final ListGrid grid, String dataJSON)
	{
		JsArray<? extends JavaScriptObject> array = JsonUtils.<JsArray<? extends JavaScriptObject>> unsafeEval(dataJSON);
		ListGridRecord[] data = new ListGridRecord[array.length()];
		for (int r = 0; r < data.length; r++)
		{
			data[r] = new ListGridRecord(array.get(r));
		}
		grid.setData(data);
	}

	private static native JavaScriptObject[] toArray(JavaScriptObject fields) /*-{
		var properties = Object.keys(fields);
		var fieldArray = new Array(properties.length);
		properties.forEach(function(key, index) {

			var fieldProps = Object.keys(fields[key]);
			for (var p = 0; p < fieldProps.length; p++) {
				if (fieldProps[p] === 'validators'
						|| fieldProps[p].charAt(0) === '$'
						|| fieldProps[p] === 'detail')
					delete fields[key][fieldProps[p]];
			}

			fieldArray[index] = fields[key];
		});

		return fieldArray;
	}-*/;

}