package com.hp.cp.pm.gwt.ui.client.data.ds;

import com.hp.cp.pm.gwt.ui.client.data.PropertyContext;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.data.RecordList;
import com.smartgwt.client.types.DSProtocol;
import com.smartgwt.client.widgets.grid.ListGridRecord;

public class PMClientDataSource extends PMDataSource {
	private RecordList data = new RecordList();
	
	public PMClientDataSource(PropertyContext propertyContext) {
		super(propertyContext);
		setDataProtocol(DSProtocol.CLIENTCUSTOM);
	}
	
	public PMClientDataSource(String id, PropertyContext propertyContext) {
		super(id, propertyContext);
		setDataProtocol(DSProtocol.CLIENTCUSTOM);
	}
	
	public void setData(RecordList records) {
		data = records;
	}
	
	public void setData(Record[] records) {
		setData(new RecordList(records));
	}
	
	public RecordList getRecordList() {
		return data;
	}
	
	@Override
	protected Object transformRequest(DSRequest request) {
		DSResponse response = new DSResponse(); 
		response.setOperationType(request.getOperationType());
		ListGridRecord record;
		Object key;
		
		switch (request.getOperationType()) {
		case FETCH:
			response.setData(data.toArray());
			response.setStartRow(0);
			response.setEndRow(data.getLength());
			response.setTotalRows(data.getLength());
			response.setStatus(0);
			break;
			
		case ADD:
			record = new ListGridRecord(request.getData());
			data.add(record);
			
			response.setData(record);
			response.setStartRow(data.getLength() - 1);
			response.setEndRow(data.getLength());
			response.setTotalRows(data.getLength());
			response.setStatus(0);

			break;
			
		case UPDATE:
			record = new ListGridRecord(request.getData());
			key = record.getAttributeAsObject(getPrimaryKeyFieldName());
			Record originalRecord = data.find(getPrimaryKeyFieldName(), key);
			int index = data.indexOf(originalRecord);
			data.set(index, record);

			response.setData(record);
			response.setStatus(0);
			break;
			
		case REMOVE:
			record = new ListGridRecord(request.getData());
			data.remove(record);

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

		return null;
	}
}
