package standalone.client;

import com.google.gwt.core.client.EntryPoint;
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.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.types.DSDataFormat;
import com.smartgwt.client.types.DSProtocol;
import com.smartgwt.client.util.SC;
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.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.VLayout;

public class Standalone_smartgwt implements EntryPoint {
	private ListGrid left;
	private Record[] testData = new Record[] { new Record() {
		{
			setAttribute("id", 1);
			setAttribute("value", "value1");
		}
	}, new Record() {
		{
			setAttribute("id", 2);
			setAttribute("value", "value2");
		}
	}, new Record() {
		{
			setAttribute("id", 3);
			setAttribute("value", "value3");
		}
	} };

	public void onModuleLoad() {
		final DataSourceIntegerField idField = new DataSourceIntegerField("id");
		idField.setPrimaryKey(true);
		final DataSourceTextField valueField = new DataSourceTextField("value");
		DataSource clientCustom = new DataSource() {
			{
				setDataProtocol(DSProtocol.CLIENTCUSTOM);
				setDataFormat(DSDataFormat.CUSTOM);
				setClientOnly(false);
				setFields(new DataSourceField[] { idField, valueField });
			}

			@Override
			protected Object transformRequest(DSRequest request) {
				String requestId = request.getRequestId();
				DSResponse response = new DSResponse();
				response.setAttribute("clientContext",
						request.getAttributeAsObject("clientContext"));
				// Assume success
				response.setStatus(0);
				switch (request.getOperationType()) {
				case FETCH:
					response.setData(testData);
					processResponse(requestId, response);
					break;
				default:
					// Operation not implemented.
					break;
				}
				return request.getData();
			}
		};
		left = new ListGrid();
		left.setDataSource(clientCustom);
		left.setAutoFetchData(true);
		Button button = new Button("Get Selected");
		button.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				ListGridRecord[] selectedRecords = left.getSelectedRecords();
				SC.say(selectedRecords.length + " records selected");
			}
		});

		RootPanel rootPanel = RootPanel.get("smartgwtbody");
		VLayout layout = new VLayout();
		layout.setBorder("1px solid grey");
		layout.addMember(left);
		layout.addMember(button);
		rootPanel.add(layout);
	}
}
