package com.hp.isomorphic.client.issues;

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.RecordList;
import com.smartgwt.client.types.DSProtocol;
import com.smartgwt.client.types.FieldType;

public class FullGridSampleDataSource extends DataSource {
	private RecordList data = null;
	
	public FullGridSampleDataSource(RecordList records) {
		DataSourceField dsIdField = new DataSourceField("idField", FieldType.TEXT, "ID");
		DataSourceField dsStatusField = new DataSourceField("statusField", FieldType.TEXT, "Status");
		DataSourceField dscontentField = new DataSourceField("contentField", FieldType.TEXT, "Text");
		DataSourceField dsSortField = new DataSourceField("sortField", FieldType.INTEGER, "Sort");

		dsIdField.setPrimaryKey(true);
		setFields(dsIdField, dsStatusField, dscontentField, dsSortField);
		
		setDataProtocol(DSProtocol.CLIENTCUSTOM);
		
		data = records;
	}
	
	@Override
	protected Object transformRequest(DSRequest request) {
		DSResponse response = new DSResponse(); 
		response.setOperationType(request.getOperationType());
		Record record;
		Object key;
		
		switch (request.getOperationType()) {
		case FETCH:
			response.setData(data.toArray());
			response.setStartRow(0);
			response.setEndRow(data.getLength() - 1);
			response.setTotalRows(data.getLength());
			response.setStatus(0);
			break;
			
		case ADD:
			record = request.getResultSet().get(0);
			data.add(record);
			
			response.setData(record);
			response.setStartRow(data.getLength() - 1);
			response.setEndRow(data.getLength() - 1);
			response.setTotalRows(data.getLength());
			response.setStatus(0);

			break;
			
		case UPDATE:
			record = request.getResultSet().get(0);
			key = record.getAttributeAsObject("idField");
			Record originalRecord = data.find("idField", key);
			int index = data.indexOf(originalRecord);
			data.set(index, record);

			response.setData(record);
			response.setStatus(0);
			break;
			
		case REMOVE:
			record = request.getResultSet().get(0);
			data.remove(record);

			response.setData(record);
			response.setStatus(0);
			break;
			
		default:
			response.setStatus(-1);
			break;
		}
		
		processResponse(request.getRequestId(), response);

		return null;
	}
}
