package my.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import my.client.SimpleGwtRPCDS;
import my.client.SimpleGwtRPCDSRecord;
import my.client.SimpleGwtRPCDSService;

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

/**
 * 
 * @author Aleksandras Novikovas
 * @author System Tier
 * @version 1.0
 */
public class SimpleGwtRPCDSServiceImpl extends RemoteServiceServlet implements
    SimpleGwtRPCDSService {

  private static final long serialVersionUID = 1L;

  List<SimpleGwtRPCDSRecord> list = new ArrayList<SimpleGwtRPCDSRecord>();
  int id = 0;
  {
    for (; id < SimpleGwtRPCDS.LIST_SIZE; id++) {
      SimpleGwtRPCDSRecord record;
      record = new SimpleGwtRPCDSRecord();
      record.setId(id);
      record.setName("Name" + id);
      record.setDate(new Date());
      list.add(record);
    }
  }

  public List<SimpleGwtRPCDSRecord> fetch(int start, int end) {
    List<SimpleGwtRPCDSRecord> sublist = new ArrayList<SimpleGwtRPCDSRecord>();
    
    for (int i = start; i <= end; i++) {
      sublist.add(list.get(i));
    }
    System.out.println(start+":"+end);
    return sublist;
  }

  public SimpleGwtRPCDSRecord add(SimpleGwtRPCDSRecord record) {
    record.setId(id++);
    list.add(record);
    return record;
  }

  public SimpleGwtRPCDSRecord update(SimpleGwtRPCDSRecord 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(SimpleGwtRPCDSRecord 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);
      }
    }
    // return record;
  }

}
