package it.infracom.prova.server;

import it.infracom.prova.client.*;

import java.util.*;

import com.google.gwt.user.server.rpc.*;

/**
 *
 * @author Aleksandras Novikovas
 * @author System Tier
 * 
 * @author Roberto Mozzicato
 * @author Infracom IT
 * @version 2.0
 */
public class TestServiceImpl extends RemoteServiceServlet implements TestService {

	static List<TestRecord> list;

	static {
		list = new ArrayList<TestRecord>();
		TestRecord record;
		for (int i = 1; i <= 400; i++) {
			record = new TestRecord();
			record.setId(i);
			record.setName("Name " + i);
			record.setDate(new Date());
			list.add(record);
		}
	}

	public FetchResult<TestRecord> fetch(int startRow, int endRow) {
		FetchResult<TestRecord> ret = new FetchResult<TestRecord>();
		System.out.println("Received a fetch request from " + startRow + " to " + endRow);
		ArrayList<TestRecord> listaRet = new ArrayList<TestRecord>();
		int i;
		for (i = startRow; i < endRow && i < list.size(); i++) {
			listaRet.add(list.get(i));
		}
		ret.setFetchedList(listaRet);
		ret.setStartRow(startRow);
		ret.setEndRow(i);
		ret.setTotalRows(list.size());
		return ret;
	}

	public TestRecord add(TestRecord record) {
		record.setId(list.size());
		list.add(record);
		return record;
	}

	public TestRecord update(TestRecord record) {
		Integer recordId = record.getId();
		if (recordId != null) {
			int index = -1;
			for (int i = 0; i < list.size(); i++) {
				if (recordId.equals(list.get(i).getId())) {
					index = i;
					break;
				}
			}
			if (index >= 0) {
				list.set(index, record);
				return record;
			}
		}
		return null;
	}

	public void remove(TestRecord record) {
		Integer recordId = record.getId();
		if (recordId != null) {
			int index = -1;
			for (int i = 0; i < list.size(); i++) {
				if (recordId.equals(list.get(i).getId())) {
					index = i;
					break;
				}
			}
			if (index >= 0) {
				list.remove(index);
			}
		}
	}

}
