package com.portal.client.main.menu.tabs.ds;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.portal.client.beans.mgtnet.GWTMgtNetRouter;
import com.portal.client.beans.singletons.ClientSession;
import com.portal.client.beans.singletons.Logger;
import com.portal.client.beans.user.GWTUserContext;
import com.portal.client.common.components.ds.FetchResult;
import com.portal.client.common.components.ds.GwtRpcDataSource;
import com.portal.client.mgtNet.MgtNetServiceAsync;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.fields.DataSourceDateField;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.util.JSOHelper;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import java.util.List;

public class RouterDataSource extends GwtRpcDataSource {

    private static String DATA_SOURCE_ID = "RouterDataSourceDS";
    private static RouterDataSource instance = null;

    public static RouterDataSource getInstance() {
        if (instance == null) {
            instance = new RouterDataSource(DATA_SOURCE_ID);
        }

        return instance;
    }

    private RouterDataSource(String id) {
        setID(id);
        DataSourceIntegerField idDataField = new DataSourceIntegerField("id", "ID");
        idDataField.setPrimaryKey(true);
        DataSourceTextField nameDataField = new DataSourceTextField("name", "Router Name");
        nameDataField.setCanEdit(false);
        DataSourceTextField ipAddressDataField = new DataSourceTextField("ipadress", "IP Adress");
        ipAddressDataField.setCanEdit(false);
        DataSourceDateField regDateDataField = new DataSourceDateField("regdate", "Register Date");
        regDateDataField.setCanEdit(false);
        DataSourceDateField updDateDataField = new DataSourceDateField("upddate", "Update Date");
        updDateDataField.setCanEdit(false);
        setFields(idDataField, nameDataField, ipAddressDataField, regDateDataField, updDateDataField);
    }

    @Override
    protected void executeFetch(final String requestId, final DSRequest request, final DSResponse response) {
        GWTUserContext context = ClientSession.getInstance().getGWTUserContext();
        MgtNetServiceAsync service = ClientSession.getInstance().getMgtNetService();
        service.getMgtNetRouters(request.getStartRow(), request.getEndRow(), context, new AsyncCallback<FetchResult<GWTMgtNetRouter>>() {

            public void onFailure(Throwable caught) {
                response.setStatus(RPCResponse.STATUS_FAILURE);
                processResponse(requestId, response);
            }

            public void onSuccess(FetchResult<GWTMgtNetRouter> result) {
                List<GWTMgtNetRouter> listMy = result.getFetchedList();
                ListGridRecord[] list = new ListGridRecord[listMy.size()];
                for (int i = 0; i < list.length; i++) {
                    ListGridRecord record = new ListGridRecord();
                    copyValues(result.getFetchedList().get(i), record);
                    list[i] = record;
                }
                response.setData(list);
                response.setStartRow(result.getStartRow());
                response.setEndRow(result.getEndRow());
                response.setTotalRows(result.getTotalRows());
                processResponse(requestId, response);
            }
        });
    }

    @Override
    protected void executeAdd(final String requestId, final DSRequest request, final DSResponse response) {
        // Retrieve record which should be added.
        final ListGrid grid = (ListGrid) Canvas.getById("mgtNetRouterListGridId");
        grid.deselectAllRecords();
        GWTUserContext context = ClientSession.getInstance().getGWTUserContext();
        JavaScriptObject data = request.getData();
        ListGridRecord rec = new ListGridRecord(data);
        GWTMgtNetRouter gWTMgtNetRouter = new GWTMgtNetRouter();
        copyValues(rec, gWTMgtNetRouter);
        MgtNetServiceAsync service = ClientSession.getInstance().getMgtNetService();
        service.addMgtNetRouters(gWTMgtNetRouter, context, new AsyncCallback<GWTMgtNetRouter>() {

            public void onFailure(Throwable caught) {
                response.setStatus(RPCResponse.STATUS_FAILURE);
                processResponse(requestId, response);
            }

            public void onSuccess(GWTMgtNetRouter result) {
                ListGridRecord[] list = new ListGridRecord[1];
                ListGridRecord newRec = new ListGridRecord();
                copyValues(result, newRec);
                list[0] = newRec;
                response.setData(list);
                processResponse(requestId, response);
                grid.selectRecord(newRec);
            }
        });
    }

    @Override
    protected void executeUpdate(final String requestId, final DSRequest request, final DSResponse response) {

        final ListGrid grid = (ListGrid) Canvas.getById("mgtNetRouterListGridId");
        grid.deselectAllRecords();
        GWTUserContext context = ClientSession.getInstance().getGWTUserContext();
        ListGridRecord rec = getEditedRecord(request);
        GWTMgtNetRouter testRec = new GWTMgtNetRouter();
        copyValues(rec, testRec);
        MgtNetServiceAsync service = ClientSession.getInstance().getMgtNetService();
        service.editMgtNetRouters(testRec, context, new AsyncCallback<GWTMgtNetRouter>() {

            public void onFailure(Throwable caught) {
                response.setStatus(RPCResponse.STATUS_FAILURE);
                processResponse(requestId, response);
            }

            public void onSuccess(GWTMgtNetRouter result) {
                ListGridRecord[] list = new ListGridRecord[1];
                ListGridRecord updRec = new ListGridRecord();
                copyValues(result, updRec);
                list[0] = updRec;
                response.setData(list);
                processResponse(requestId, response);
                grid.selectRecord(updRec);
            }
        });
    }

    @Override
    protected void executeRemove(final String requestId, final DSRequest request, final DSResponse response) {
        // Retrieve record which should be removed.
        GWTUserContext context = ClientSession.getInstance().getGWTUserContext();
        JavaScriptObject data = request.getData();
        final ListGridRecord rec = new ListGridRecord(data);
        GWTMgtNetRouter testRec = new GWTMgtNetRouter();
        copyValues(rec, testRec);
        MgtNetServiceAsync service = ClientSession.getInstance().getMgtNetService();
        service.removeMgtNetRouters(testRec, context, new AsyncCallback() {

            public void onFailure(Throwable caught) {
                response.setStatus(RPCResponse.STATUS_FAILURE);
                processResponse(requestId, response);
            }

            public void onSuccess(Object result) {
                ListGridRecord[] list = new ListGridRecord[1];
                list[0] = rec;
                response.setData(list);
                processResponse(requestId, response);
            }
        });
    }

    public static void copyValues(ListGridRecord from, GWTMgtNetRouter to) {
        if (from.getAttributeAsInt("id") != null) {
            to.setId(new Long(from.getAttributeAsInt("id")));
        }
        if (from.getAttribute("name") != null) {
            to.setName(from.getAttribute("name"));
        }
        if (from.getAttribute("ipadress") != null) {
            to.setIpAddress(from.getAttribute("ipadress"));
        }
        if (from.getAttributeAsDate("regdate") != null) {
            to.setRegDate(from.getAttributeAsDate("regdate"));
        }
        if (from.getAttributeAsDate("upddate") != null) {
            to.setUpdDate(from.getAttributeAsDate("upddate"));
        }

    }

    public static void copyValues(GWTMgtNetRouter gWTMgtNetRouter, ListGridRecord to) {
        to.setAttribute("id", gWTMgtNetRouter.getId() == null ? -1 : gWTMgtNetRouter.getId().intValue());
        to.setAttribute("name", gWTMgtNetRouter.getName() == null ? "" : gWTMgtNetRouter.getName());
        to.setAttribute("ipadress", gWTMgtNetRouter.getIpAddress() == null ? "" : gWTMgtNetRouter.getIpAddress());
        if (gWTMgtNetRouter.getRegDate() != null) {
            to.setAttribute("regdate", gWTMgtNetRouter.getRegDate());
        }
        if (gWTMgtNetRouter.getUpdDate() != null) {
            to.setAttribute("upddate", gWTMgtNetRouter.getUpdDate());
        }
    }

    private ListGridRecord getEditedRecord(DSRequest request) {
        // Retrieving values before edit
        JavaScriptObject oldValues = request.getAttributeAsJavaScriptObject("oldValues");
        // Creating new record for combining old values with changes
        ListGridRecord newRecord = new ListGridRecord();
        // Copying properties from old record
        JSOHelper.apply(oldValues, newRecord.getJsObj());
        // Retrieving changed values
        JavaScriptObject data = request.getData();
        // Apply changes
        JSOHelper.apply(data, newRecord.getJsObj());
        return newRecord;
    }
}
