package com.systemtier.web.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.systemtier.web.client.TestService;
import com.systemtier.web.client.TestRecord;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

    static List<TestRecord> list;

    static int id;
    static {
        id = 1;
        list = new ArrayList<TestRecord> ();
        TestRecord record;
        record = new TestRecord ();
        record.setId (id++);
        record.setName ("First");
        record.setDate (new Date ());
        list.add (record);
        record = new TestRecord ();
        record.setId (id++);
        record.setName ("Second");
        record.setDate (new Date ());
        list.add (record);
        record = new TestRecord ();
        record.setId (id++);
        record.setName ("Third");
        record.setDate (new Date ());
        list.add (record);
    }

    public List<TestRecord> fetch () {
        return list;
    }

    public TestRecord add (TestRecord record) {
        record.setId (id++);
        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);
            }
        }
    }

}
