import java.util.ArrayList;
import java.util.List;

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.DataSourceSequenceField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.types.DSOperationType;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.EditorExitEvent;
import com.smartgwt.client.widgets.layout.VLayout;

public class AppEntryPoint implements EntryPoint
{
	private static ListGridRecord[] RECORDS;
	ListGrid listGrid;

	{
		List<ListGridRecord> recordList = new ArrayList<>();
		for (int i = 0; i < 30; i++)
		{
			recordList.add(mkRecord(i, "test" + i));
		}
		RECORDS = recordList.toArray(new ListGridRecord[0]);
	}

	@Override
	public void onModuleLoad()
	{
		VLayout layout = new VLayout();
		RootPanel.get().add(layout);

		DataSource dataSource = new DataSource();
		dataSource.setClientOnly(true);
		dataSource.setTestData(RECORDS);
		DataSourceField sequenceField = new DataSourceSequenceField("id", "ID");
		sequenceField.setRequired(true);
		DataSourceField textField = new DataSourceTextField("textField", "Text Field");
		dataSource.setFields(sequenceField, textField);

		listGrid = new ListGrid(dataSource);
		listGrid.setSize("500", "200");
		listGrid.setCanEdit(true);
		listGrid.setAutoFetchData(true);
		listGrid.addEditorExitHandler(this::onEditorExit);
		layout.addMember(listGrid);

		Button button = new Button("add");
		button.addClickHandler(h -> listGrid.startEditingNew());
		layout.addMember(button);
	}

	private void onEditorExit(EditorExitEvent editorExitEvent)
	{
		Record record = editorExitEvent.getRecord();
		updateCacheDate(record);
	}

	private void updateCacheDate(Record record)
	{
		DSResponse dsResponse = new DSResponse();
		dsResponse.setData(record);

		DSRequest dsRequest = new DSRequest();
		dsRequest.setOperationType(DSOperationType.UPDATE);

		//XXX: updateCaches would cause scrollbar jumps to top in Edge,works fine on IE and Chrome, no solution now.
		listGrid.getDataSource().updateCaches(dsResponse, dsRequest);
	}

	private static final ListGridRecord mkRecord(int id, String textField)
	{
		final ListGridRecord record = new ListGridRecord();
		record.setAttribute("id", id);
		record.setAttribute("textField", textField);
		return record;
	}
}