package com.smartgwt.sample.server;

import java.util.LinkedList;
import java.util.List;

import com.isomorphic.datasource.DSRequest;
import com.isomorphic.datasource.DSResponse;
import com.isomorphic.log.Logger;

// the <serverObject> declaration in supplyItemDMI.ds.xml directs the SmartClient Java
// server libraries to find the BrancheDynamicFlagsDMI class.
// Several ways of finding or creating the DMI target are supported, including via Spring, or
// via session or request attributes.  See ServerObject.lookupStyle in the SmartClient Reference.
// You can also provide your own servlet, invoking SmartClient DMI from a Spring Controller or
// Struts Action.
public class BrancheDynamicFlagsDMI {

	Logger log = new Logger(BrancheDynamicFlagsDMI.class.getName());
	private int databaseChangeSimulator = 2;
	// By default, for a DSRequest of type "fetch", a method named "fetch" is
	// invoked. You can
	// customize this via the <serverObject> declaration.
	public DSResponse fetch(DSRequest dsRequest) throws Exception {
		log.info("procesing DMI fetch operation");
		long startRow = dsRequest.getStartRow();
		long endRow = dsRequest.getEndRow();
		List<POJO> matchingItems = new LinkedList<POJO>();
//		Long answerId = (Long) dsRequest.getCriteria().get("answerId");
		int answerId = ++databaseChangeSimulator %3;
		if (answerId == 0) {
			matchingItems.add(new POJO(1, 1, "ODP1", "Text1"));
			matchingItems.add(new POJO(2, 1, "ODP2", "Text2"));
			matchingItems.add(new POJO(3, 1, "ODP3", "Text3"));
			matchingItems.add(new POJO(4, 1, "ODP4", "Text4"));
		} else if (answerId == 1) {
			matchingItems.add(new POJO(5, 2, "ODP1", "Text5"));
			matchingItems.add(new POJO(6, 2, "ODP2", "Text6"));
			matchingItems.add(new POJO(7, 2, "ODP3", "Text7"));
		} else if (answerId == 2) {
			matchingItems.add(new POJO(8, 3, "ODP1", "Text8"));
			matchingItems.add(new POJO(9, 3, "ODP2", "Text9"));
		}

		long totalRows = matchingItems.size();
		DSResponse dsResponse = new DSResponse();
		dsResponse.setSuccess();
		dsResponse.setDataSource(dsRequest.getDataSource());
		dsResponse.setTotalRows(totalRows);
		dsResponse.setStartRow(startRow);

		endRow = Math.min(endRow, totalRows);
		dsResponse.setEndRow(endRow);

		// just return the List of matching beans
		dsResponse.setData(matchingItems);

		return dsResponse;
	}
} 