// Description: 
// Isomorphic thread: 
// Resolution: 

package com.hp.isomorphic.client.issues;

import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
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.Record;
import com.smartgwt.client.data.ResultSet;
import com.smartgwt.client.types.DSOperationType;
import com.smartgwt.client.types.FetchMode;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.OperatorId;
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;
import com.smartgwt.client.widgets.grid.events.SelectionUpdatedEvent;
import com.smartgwt.client.widgets.grid.events.SelectionUpdatedHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;

public class FullGridSample extends VLayout {
	private ListGrid grid;
	
	public FullGridSample() {
		grid = new ListGrid();
		
		ListGridField gridIdField = new ListGridField("idField", "ID", 40);
		gridIdField.setCanDragResize(false);
		gridIdField.setCanReorder(false);
		gridIdField.setType(ListGridFieldType.INTEGER);
		
		ListGridField gridStatusField = new ListGridField("statusField", "Status", 80);

		ListGridField contentField = new ListGridField("contentField", "Content", 300);

		ListGridField sortField = new ListGridField("sortField", "Sort", 100);

		grid.setFields(gridIdField, gridStatusField, contentField, sortField);
		
		final DataSource ds = new FullGridSampleDataSource();

		grid.setShowAllRecords(false);
		grid.setAutoFetchData(true);
		grid.setDataSource(ds);
		grid.setSelectionType(SelectionStyle.MULTIPLE);
		grid.setSortField("sortField");
		grid.setGroupByMaxRecords(2500);
		grid.setDataFetchMode(FetchMode.BASIC);
		ResultSet dataProperties = new ResultSet();
        dataProperties.setUpdatePartialCache(false);
        grid.setDataProperties(dataProperties);
        
		AdvancedCriteria criteria = new AdvancedCriteria("contentField", OperatorId.NOT_CONTAINS, " - update");
		grid.setCriteria(criteria);

		grid.addSelectionUpdatedHandler(new SelectionUpdatedHandler() {
			@Override
			public void onSelectionUpdated(SelectionUpdatedEvent event) {
				GWT.log("Grid selection changed: " + grid.getSelectedRecords().length);
			}
		});
		
		addMember(grid);
		
		HLayout buttonBar = new HLayout();
		buttonBar.setAutoHeight();
		buttonBar.setAutoWidth();
		
		Button button = new Button("Add record");
		button.setWidth("150px");
		button.setHeight("40px");
		button.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				ListGridRecord record = FullGridSampleDataSource.createRecord();
				updateCache(grid, record, DSOperationType.ADD);
			}
		});
		
		buttonBar.addMember(button);
		
		button = new Button("Update content field");
		button.setWidth("150px");
		button.setHeight("40px");
		button.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				for (ListGridRecord record: grid.getSelectedRecords()) {
					String recordId = record.getAttributeAsString("idField");
					Record updatedRecord = findRecord(grid, recordId);
					updatedRecord.setAttribute("contentField", record.getAttributeAsString("contentField") + " - update");
					updateCache(grid, updatedRecord, DSOperationType.UPDATE);
				}
			}
		});
		
		buttonBar.addMember(button);
		
		button = new Button("Update sort field");
		button.setWidth("150px");
		button.setHeight("40px");
		button.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				for (ListGridRecord record: grid.getSelectedRecords()) {
					String recordId = record.getAttributeAsString("idField");
					Record updatedRecord = findRecord(grid, recordId);
					updatedRecord.setAttribute("sortField", FullGridSampleDataSource.getSortValue());
					updateCache(grid, updatedRecord, DSOperationType.UPDATE);
				}
			}
		});
		
		buttonBar.addMember(button);
		
		button = new Button("Update status field");
		button.setWidth("150px");
		button.setHeight("40px");
		button.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				for (ListGridRecord record: grid.getSelectedRecords()) {
					String recordId = record.getAttributeAsString("idField");
					Record updatedRecord = findRecord(grid, recordId);
					updatedRecord.setAttribute("statusField", FullGridSampleDataSource.getStatusValue());
					updateCache(grid, updatedRecord, DSOperationType.UPDATE);
				}
			}
		});
		
		buttonBar.addMember(button);
		
		addMember(buttonBar);
	}
	
	private static void updateCache(ListGrid grid, Record record, DSOperationType opType) {
		DSRequest request = new DSRequest();
		request.setOperationType(opType);

		DSResponse response = new DSResponse();
		ListGridRecord lgRecord = new ListGridRecord();
		for (String attrName: record.getAttributes()) {
			lgRecord.setAttribute(attrName, record.getAttributeAsObject(attrName));
		}
			
		response.setData(new ListGridRecord[]{ lgRecord });
		response.setOperationType(opType);
		response.setStatus(0);

		if (opType == DSOperationType.ADD) {
			ResultSet originalResultSet = grid.getOriginalResultSet();
			int rowCount = originalResultSet.getLength();
			request.setStartRow(rowCount);
			request.setEndRow(rowCount + 1);
			response.setStartRow(rowCount);
			response.setEndRow(rowCount + 1);
			response.setTotalRows(rowCount + 1);
		}

		DataSource dataSource = grid.getDataSource();
		dataSource.updateCaches(response, request);
		GWT.log("Updated: " + grid.getSelectedRecords().length);
	}
	
	private static Record findRecord(ListGrid grid, String recordId) {
		Record record = null;
		ResultSet resultSet = grid.getOriginalResultSet();
		if (resultSet != null) {
			if (resultSet.lengthIsKnown()) {
				record = resultSet.find("idField", recordId);
				if (record != null) {
					record = grid.getDataSource().copyRecord(record);
				}
			}
		}
		return record;
	}

//	private static void updateData(ListGrid grid, Record record, DSOperationType opType) {
//    	boolean keepInView = false;
//    	
//    	if (!grid.isGrouped()) {
//	    	int recordIndex = grid.getRecordIndex(record);
//	    	GWT.log("recordIndex=" + recordIndex); //$NON-NLS-1$
//	    	
//	    	Integer[] viewPort = grid.getVisibleRows();
//	    	GWT.log("viewPort=" + Arrays.toString(viewPort)); //$NON-NLS-1$
//	    	
//	    	boolean isSelected = grid.isSelected(grid.getRecord(recordIndex));
//	    	GWT.log("isSelected=" + isSelected); //$NON-NLS-1$
//	    	
//	    	if (isSelected && grid.getSelectedRecords().length == 1) {
//	        	boolean inView = false;
//	        	if (recordIndex >= viewPort[0] && recordIndex <= viewPort[1]) {
//	        		inView = true;
//	        	}
//	        	GWT.log("inView=" + inView); //$NON-NLS-1$
//	        	
//	        	if (inView) {
//	        		keepInView = true;
//	        	}
//	    	}
//    	}
//    	
//    	updateCache(grid, record, opType);
//    	
//    	if (keepInView) {
//			String recordId = record.getAttributeAsString("idField");
//    		Record newRecord = findRecord(grid, recordId);
//        	int newRecordIndex = grid.getRecordIndex(newRecord);
//        	GWT.log("new recordIndex=" + newRecordIndex); //$NON-NLS-1$
//        	grid.scrollToRow(newRecordIndex);
//    	}
//	}
}
