package de.scai.client.ticket1445.defect.model;

import com.google.gwt.core.client.Scheduler;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.util.JSOHelper;
import com.smartgwt.client.widgets.grid.ListGridRecord;

import java.util.List;

public abstract class BugReportDataSource extends GwtRpcDataSource {

    protected List<ListGridRecord> data;

    protected abstract void initData();

    @Override
    protected void executeFetch(final String pRequestId, final DSRequest pRequest, final DSResponse pResponse) {
        Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
            @Override
            public void execute() {
                ListGridRecord[] listGridRecords = data.toArray(new ListGridRecord[data.size()]);
                pResponse.setData(listGridRecords);
                processResponse(pRequestId, pResponse);
            }
        });
    }

    @Override
    protected void executeAdd(final String pRequestId, final DSRequest pRequest, final DSResponse pResponse) {
        final ListGridRecord record = new ListGridRecord();
        JSOHelper.apply(pRequest.getData(), record.getJsObj());
        Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
            @Override
            public void execute() {
                ListGridRecord[] listGridRecords = new ListGridRecord[1];

                record.setAttribute(getPrimaryKeyFieldName(), data.size());

                data.add(record);

                listGridRecords[0] = record;
                pResponse.setData(listGridRecords);

                processResponse(pRequestId, pResponse);
            }
        });
    }

    @Override
    protected void executeUpdate(final String pRequestId, final DSRequest pRequest, final DSResponse pResponse) {
        final ListGridRecord record = new ListGridRecord();
        JSOHelper.apply(pRequest.getData(), record.getJsObj());
        Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
            @Override
            public void execute() {
                ListGridRecord[] listGridRecords = new ListGridRecord[1];

                data.set(record.getAttributeAsInt(getPrimaryKeyFieldName()), record);

                listGridRecords[0] = record;

                pResponse.setData(listGridRecords);
                processResponse(pRequestId, pResponse);
            }
        });
    }

    @Override
    protected void executeRemove(final String pRequestId, final DSRequest pRequest, final DSResponse pResponse) {
        Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
            @Override
            public void execute() {
                processResponse(pRequestId, pResponse);
            }
        });
    }

}
