/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */
package com.queplix.core.client.frames.adhoc;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.WindowResizeListener;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.queplix.core.client.app.rpc.RPC;
import com.queplix.core.client.app.vo.AdhocPrintRequestObject;
import com.queplix.core.client.app.vo.AdhocSearchGridRecordsRequest;
import com.queplix.core.client.app.vo.EntityElement;
import com.queplix.core.client.app.vo.FieldMeta;
import com.queplix.core.client.app.vo.GridMeta;
import com.queplix.core.client.app.vo.GridSearchProperties;
import com.queplix.core.client.app.vo.LoadReportResponseObject;
import com.queplix.core.client.app.vo.MetaData;
import com.queplix.core.client.app.vo.SaveAdhocReportRequestObject;
import com.queplix.core.client.app.vo.SearchGridRecordsResponseObject;
import com.queplix.core.client.app.vo.SortFieldImpl;
import com.queplix.core.client.common.StringUtil;
import com.queplix.core.client.common.crossframes.AdhocData;
import com.queplix.core.client.common.event.Event;
import com.queplix.core.client.common.event.EventListener;
import com.queplix.core.client.common.event.EventSource;
import com.queplix.core.client.common.ui.DialogHelper;
import com.queplix.core.client.common.ui.OkayCancelPopup;
import com.queplix.core.client.common.ui.WindowHelper;
import com.queplix.core.client.common.ui.grid.SortColumn;
import com.queplix.core.client.controls.QButton;
import com.queplix.core.client.controls.grid.QGrid;
import com.queplix.core.client.controls.grid.QGridController;
import com.queplix.core.client.controls.grid.QGridModel;
import com.queplix.core.client.controls.grid.QGridView;
import com.queplix.core.client.frames.QFrame;
import com.queplix.core.client.i18n.I18N;

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

/**
 * This frame allows to create ad hoc own designed reports.
 *
 * @author Aliaksandr Melnik
 * @author Sergey Kozmin
 * @since 13 Nov 2006
 */
public class AdhocReportFrame extends VerticalPanel
        implements QFrame, EventListener, WindowResizeListener {
    private static final String REPORT_LOADED_LABEL = I18N.getMessages()
            .adhocReportLoaded();

    /**
     * Dialog saving messages
     */
    private static final String SAVE_REPORT_MESSAGE = I18N.getMessages()
            .adhocSaveReport();
    private static final String NONE_REPORT_NAME = I18N.getMessages()
            .adhocNoneReportName();
    private static final String REPORT_NAME_MESSAGE = I18N.getMessages()
            .adhocReportName();
    private static final String FILL_REPORT_NAME_FIRST_MESSAGE = I18N
            .getMessages().adhocFillReportFirstError();
    private static final String SUCCESSFULLY_SAVED_REPORT_MESSAGE = I18N
            .getMessages().adhocReportsSavedSuccesfully();

    /**
     * Field renaming messages
     */
    private static final String FIELD_NAME_MESSAGE = I18N.getMessages()
            .adhocSaveReport();
    private static final String NEW_FIELD_NAME_INPUT_MESSAGE = I18N
            .getMessages().adhocNewFieldName();
    private static final String FILL_FIELD_NAME_FIRST_MESSAGE = I18N
            .getMessages().adhocFillFieldFirstError();

    /**
     * Button names
     */
    private static final String CLEAR_ALL_BUTTON = I18N.getMessages()
            .adhocClearAllColumnButton();
    private static final String CLEAR_ALL_TOOLTIP_BUTTON = I18N.getMessages()
            .adhocClearAllColumnButtonTooltip();
    private static final String RUN_REPORT_BUTTON = I18N.getMessages()
            .adhocRunReportButton();
    private static final String RUN_REPORT_TOOLTIP_BUTTON = I18N.getMessages()
            .adhocRunReportButtonTooltip();
    private static final String DELETE_COLUMN_BUTTON = I18N.getMessages()
            .adhocDeleteColumnButton();
    private static final String DELETE_COLUMN_TOOLTIP_BUTTON = I18N
            .getMessages().adhocDeleteColumnButtonTooltip();
    private static final String RENAME_COLUMN_BUTTON = I18N.getMessages()
            .adhocRenameColumnButton();
    private static final String RENAME_COLUMN_TOOLTIP_BUTTON = I18N
            .getMessages().adhocRenameColumnButtonTooltip();
    private static final String SAVE_REPORT_BUTTON = I18N.getMessages()
            .adhocSaveReportButton();
    private static final String SAVE_REPORT_TOOLTIP_BUTTON = I18N.getMessages()
            .adhocSaveReportButtonTooltip();
    private static final String LOAD_REPORT_BUTTON = I18N.getMessages()
            .adhocLoadReportButton();
    private static final String LOAD_REPORT_TOOLTIP_BUTTON = I18N.getMessages()
            .adhocLoadReportButtonTooltip();
    private static final String MOVE_COLUMN_LEFT_BUTTON = "&lt;&lt;";
    private static final String MOVE_COLUMN_LEFT_TOOLTIP_BUTTON = I18N
            .getMessages().adhocMoveColumnToLeftButtonTooltip();
    private static final String MOVE_COLUMN_RIGHT_BUTTON = "&gt;&gt;";
    private static final String MOVE_COLUMN_RIGHT_TOOLTIP_BUTTON = I18N
            .getMessages().adhocMoveColumnToRightButtonTooltip();

    private static final String REPORT_MAY_BE_INCORRECT_WARNING = I18N
            .getMessages().adhocReportIncorrectWarning();

    private static final String HTML_TYPE = "html";
    private static final String WORD_TYPE = "word";
    private static final String EXCEL_TYPE = "excel";

    private QButton clearAllButton;
    private QButton runButton;
    private QButton moveLeftButton;
    private QButton delButton;
    private QButton renButton;
    private QButton moveRightButton;
    private QButton saveButton;
    private QButton loadButton;
    private Label loadedReportLabel;

    private List/*]<AdhocData>[*/ reportElements
            = new ArrayList/*]<AdhocData>[*/();

    private SingleLineInputDialog saveReportPopup;
    private LoadingReportDialog loadReportPopup;
    private SingleLineInputDialog fieldRenamingPopup;

    private AdhocPrintRequestObject printRequest;
    private SaveAdhocReportRequestObject saveReportRequest;

    //    private TextBox reportNameTextBox;
    private HorizontalPanel buttonsPanel;
    private FrameLinks frameLinks;

    /**
     * Application metaData
     */
    private MetaData metaData;
    /**
     * is this form active
     */
    private boolean isActive = false;
    /**
     * main adhocGrid
     */
    private QGrid adhocGrid;

    /**
     * was adhocGrid elements changed
     */
    private boolean wasElementsChanged = true;

    // -------------------- public events ------------------------
    public static interface Events extends FrameLinks.Events {
        Event ELEMENT_REMOVED_EVENT = new Event();
        Event EXPORT_GRID_HTML = new Event();
        Event EXPORT_GRID_WORD = new Event();
        Event EXPORT_GRID_EXCEL = new Event();
        Event REPORT_RUN = new Event();
        Event SAVE_REPORT = new Event();
        Event/*]<LoadReportResponseObject>[*/ REPORT_LOADED
                = new Event/*]<LoadReportResponseObject>[*/();
    }

    private EventSource eventSource = new EventSource(this);

    public EventSource getEventSource() {
        return eventSource;
    }
    // ----------------- end of public events --------------------

    public AdhocReportFrame(MetaData metaData) {
        this.metaData = metaData;
        initGUI();
        addListeners();
        setButtonsState();
    }

    public int reportElementsSize() {
        return reportElements.size();
    }

    public void addAllReportElements(List data) {
        for(int i = 0; i < data.size(); i++) {
            AdhocData adhocData = (AdhocData) data.get(i);
            reportElements.add(adhocData.cloneElement());
        }
        wasElementsChanged = true;
        refresh();
    }

    public void addReportElement(AdhocData data) {
        reportElements.add(data.cloneElement());
        wasElementsChanged = true;
        refresh();
    }

    public void removeReportElement(AdhocData data) {
        reportElements.remove(data);
        wasElementsChanged = true;
        refresh();
    }

    public void moveReportElement(int fromPos, int toPos) {
        if(fromPos != toPos) {
            reportElements.add(toPos, reportElements.remove(fromPos));
            wasElementsChanged = true;
            refresh();
        }
    }

    private void removeReportElement(int index) {
        reportElements.remove(index);
        wasElementsChanged = true;
        refresh();
    }

    private void removeAllReportElements() {
        reportElements.clear();
        wasElementsChanged = true;
        refresh();
    }

    private void removeAllElementsWithNotifications() {
        int size = reportElements.size();
        for(int i = 0; i < size; i++) {
            Object element = reportElements.remove(0);
            Events.ELEMENT_REMOVED_EVENT.setData(element);
            eventSource.fireEvent(Events.ELEMENT_REMOVED_EVENT);
            reportElements.remove(element);
        }
        wasElementsChanged = true;
        refresh();
    }

    private void setColumnSelected(int column) {
        adhocGrid.getView().setSelectedColumn(column);
    }

    private void setFieldCaption() {
        int selectedColumn = adhocGrid.getView().getSelectedColumn();
        AdhocData data = (AdhocData) reportElements.get(selectedColumn);
        data.getFieldSent().setCaption(getFieldRenamingPopup().getInputText());

        wasElementsChanged = true;
        refreshGrid();
    }

    private void refresh() {
        setButtonsState();
        refreshGrid();
    }

    private void refreshGrid() {
        if(isActive) {
            if(wasElementsChanged) {
                FieldMeta[] metas = new FieldMeta[reportElements.size()];
                long[] selectedElements = new long[metas.length];

                for(int i = 0; i < reportElements.size(); i++) {
                    selectedElements[i] = i;
                    AdhocData reportData = (AdhocData) reportElements.get(i);
                    metas[i] = reportData.getFieldSent();
                }
                GridMeta gm = new GridMeta(metas, selectedElements);
                adhocGrid.getModel().setGridData(null);
                adhocGrid.getModel().setMetaData(gm);

                //reset report state
                loadedReportLabel.setText(
                        REPORT_LOADED_LABEL + NONE_REPORT_NAME);
                QGridView gridView = adhocGrid.getView();
                gridView.setOffsetWidth(Window.getClientWidth());
                setHeight(StringUtil.pixelToSize(Window.getClientHeight()));
                wasElementsChanged = false;
            }
        }
    }

    public void onEvent(Event event, Widget sender) {
        if(QGridController.Events.GRID_COLUMN_SELECTED == event) {
            setButtonsState();
        } else if(QGridController.Events.GRID_EXPORT_TO_WORD == event) {
            getEventSource().fireEvent(Events.EXPORT_GRID_WORD);
        } else if(QGridController.Events.GRID_EXPORT_TO_EXCEL == event) {
            getEventSource().fireEvent(Events.EXPORT_GRID_EXCEL);
        } else if(QGridController.Events.GRID_PRINT == event) {
            getEventSource().fireEvent(Events.EXPORT_GRID_HTML);
        } else if(QGridController.Events.GRID_REFRESH == event
                || QGridController.Events.GRID_NEED_DATA == event) {
            if(adhocGrid.getModel().getModelRowCount() > 0) {
                getEventSource().fireEvent(Events.REPORT_RUN);
            }
        }
    }

    private void setButtonsState() {
        if(isActive) {
            int selectedColumn = adhocGrid.getView().getSelectedColumn();
            int elementsSize = reportElements.size();

            moveLeftButton.setEnabled(selectedColumn >= 1);
            moveRightButton.setEnabled((selectedColumn < elementsSize - 1) && (
                    selectedColumn >= 0));
            delButton.setEnabled(selectedColumn >= 0);
            renButton.setEnabled(selectedColumn >= 0);

            clearAllButton.setEnabled(elementsSize > 0);

            runButton.setEnabled(elementsSize > 0);
            saveButton.setEnabled(elementsSize > 0);
        }
    }

    private void addListeners() {
        clearAllButton.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                removeAllElementsWithNotifications();
            }
        });
        runButton.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                getEventSource().fireEvent(Events.REPORT_RUN);
            }
        });
        moveLeftButton.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                int selectedColumn = adhocGrid.getView()
                        .getSelectedColumn();//selected column is more than 0, otherwise see column selection events
                moveReportElement(selectedColumn, selectedColumn - 1);
                setColumnSelected(selectedColumn - 1);
            }
        });
        delButton.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                int selectedColumn = adhocGrid.getView().getSelectedColumn();
                Events.ELEMENT_REMOVED_EVENT.setData(reportElements.get(
                        selectedColumn));
                eventSource.fireEvent(Events.ELEMENT_REMOVED_EVENT);

                removeReportElement(selectedColumn);
            }
        });
        renButton.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                int selectedColumn = adhocGrid.getView().getSelectedColumn();
                AdhocData data = (AdhocData) reportElements.get(selectedColumn);

                getFieldRenamingPopup().setInputText(
                        data.getFieldSent().getCaption());
                getFieldRenamingPopup().show(renButton);
            }
        });
        moveRightButton.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                int selectedColumn = adhocGrid.getView().getSelectedColumn();
                moveReportElement(selectedColumn, selectedColumn + 1);
                setColumnSelected(selectedColumn + 1);
            }
        });
        saveButton.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                getSaveReportPopup().reset();
                getSaveReportPopup().show(saveButton);
            }
        });
        loadButton.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                getLoadedReportsDialog().showReportList();
            }
        });
        adhocGrid.getController().getEventSource().addEventListener(this);
    }

    private SingleLineInputDialog getSaveReportPopup() {
        if(saveReportPopup == null) {
            saveReportPopup = createSaveReportPopup();
        }
        return saveReportPopup;
    }

    private SingleLineInputDialog createSaveReportPopup() {
        final SingleLineInputDialog dialog = new SingleLineInputDialog(
                SAVE_REPORT_MESSAGE, REPORT_NAME_MESSAGE, false);

        dialog.getEventSource().addEventListener(new EventListener() {
            public void onEvent(Event event, Widget sender) {
                if(event == OkayCancelPopup.Events.OK) {
                    if(!StringUtil.isStringEmpty(dialog.getInputText())) {
                        eventSource.fireEvent(Events.SAVE_REPORT);
                    } else {
                        DialogHelper.showModalMessageDialog(
                                FILL_REPORT_NAME_FIRST_MESSAGE);
                    }
                }
            }
        });

        return dialog;
    }

    private SingleLineInputDialog getFieldRenamingPopup() {
        if(fieldRenamingPopup == null) {
            fieldRenamingPopup = createFieldRenamingPopup();
        }
        return fieldRenamingPopup;
    }

    private SingleLineInputDialog createFieldRenamingPopup() {
        final SingleLineInputDialog dialog = new SingleLineInputDialog(
                FIELD_NAME_MESSAGE, NEW_FIELD_NAME_INPUT_MESSAGE, false);

        dialog.getEventSource().addEventListener(new EventListener() {
            public void onEvent(Event event, Widget sender) {
                if(event == OkayCancelPopup.Events.OK) {
                    if(!StringUtil.isStringEmpty(dialog.getInputText())) {
                        setFieldCaption();
                    } else {
                        DialogHelper.showModalMessageDialog(
                                FILL_FIELD_NAME_FIRST_MESSAGE);
                    }
                }
            }
        });

        return dialog;
    }

    private LoadingReportDialog getLoadedReportsDialog() {
        if(loadReportPopup == null) {
            loadReportPopup = new LoadingReportDialog(
                    metaData.getAdhocReportsMeta(), new LoadReportCallback());
        }
        return loadReportPopup;
    }

    public void runReport(List filters) {
        RPC.QAsyncCallback callback = new SearchGridRecordsAsyncCallback();
        AdhocSearchGridRecordsRequest request
                = new AdhocSearchGridRecordsRequest();

        QGridModel model = adhocGrid.getModel();
        GridSearchProperties props = new
                GridSearchProperties(model.isCounterToggledOn(),
                (int) model.getCurrentPage(),
                model.getPageSize(), null);

        request.setFields(reportElementsToRequestElements());
        request.setEntityFilters(filters);
        SortColumn col = model.getSortColumn();
        if(col != null) {
            AdhocData element = (AdhocData) reportElements.get(
                    col.getColumnIndex());
            String formId = metaData.getFormID(element.getFormIndex());
            String key = EntityElement.getElementKey(formId,
                    element.getFieldSent().getFieldID());
            props.setSortField(new SortFieldImpl(key,
                    model.getSortField().getSortOrder()));
        }
        request.setProps(props);

        RPC.getRPC().customEntitiesFieldsSearch(request, callback);
    }

    public void exportGridToExcel(List filters) {
        exportGrid(filters, EXCEL_TYPE);
    }

    public void exportGridToWord(List filters) {
        exportGrid(filters, WORD_TYPE);
    }

    public void exportGridToHtml(List filters) {
        exportGrid(filters, HTML_TYPE);
    }

    private void exportGrid(List filters, String exportType) {
        long prcId = generateUniqueProcessId();
        PrintCallback callback = new PrintCallback(exportType, prcId, false);
        if(printRequest == null) {
            printRequest = new AdhocPrintRequestObject();
        }
        printRequest = new AdhocPrintRequestObject(filters,
                reportElementsToRequestElements(), prcId);
        RPC.getRPC().customEntitiesFieldsReport(printRequest, callback);
    }

    private static long generateUniqueProcessId() {
        return System.currentTimeMillis();
    }

    /**
     * Load report with the given report name and elements
     *
     * @param reportName   report name
     * @param reportFields elements of {@link com.queplix.core.client.common.crossframes.AdhocData}
     */
    public void loadReport(String reportName, List reportFields) {
        removeAllReportElements();
        addAllReportElements(reportFields);
        loadedReportLabel.setText(REPORT_LOADED_LABEL + reportName);
    }

    public void saveAdhocReport(List filters) {
        RPC.QAsyncCallback callback = new SaveReportCallback();
        if(saveReportRequest == null) {
            saveReportRequest = new SaveAdhocReportRequestObject();
        }
        saveReportRequest.init(filters, reportElementsToRequestElements(),
                getSaveReportPopup().getInputText());
        RPC.getRPC().saveReport(saveReportRequest, callback);
    }

    private List/*]<ReportElement>[*/ reportElementsToRequestElements() {
        ArrayList/*]<ReportElement>[*/ fields
                = new ArrayList/*]<ReportElement>[*/();
        for(int i = 0; i < reportElements.size(); i++) {
            AdhocData data = (AdhocData) reportElements.get(i);
            String formId = metaData.getFormID(data.getFormIndex());
            fields.add(new EntityElement(formId,
                    data.getFieldSent().getFieldID(),
                    data.getFieldSent().getCaption()));
        }
        return fields;
    }

    private void initGUI() {
        setWidth("100%");

        frameLinks = new FrameLinks();
        frameLinks.getEventSource().addEventListener(eventSource);
        add(frameLinks);
        setCellHorizontalAlignment(frameLinks,
                HasHorizontalAlignment.ALIGN_RIGHT);

        buttonsPanel = new HorizontalPanel();
        clearAllButton = new QButton(CLEAR_ALL_BUTTON,
                CLEAR_ALL_TOOLTIP_BUTTON);
        buttonsPanel.add(clearAllButton);
        runButton = new QButton(RUN_REPORT_BUTTON, RUN_REPORT_TOOLTIP_BUTTON);
        buttonsPanel.add(runButton);
        moveLeftButton = new QButton(MOVE_COLUMN_LEFT_BUTTON,
                MOVE_COLUMN_LEFT_TOOLTIP_BUTTON);
        moveLeftButton.setEnabled(false);
        buttonsPanel.add(moveLeftButton);
        delButton = new QButton(DELETE_COLUMN_BUTTON,
                DELETE_COLUMN_TOOLTIP_BUTTON);
        buttonsPanel.add(delButton);
        renButton = new QButton(RENAME_COLUMN_BUTTON,
                RENAME_COLUMN_TOOLTIP_BUTTON);
        buttonsPanel.add(renButton);
        moveRightButton = new QButton(MOVE_COLUMN_RIGHT_BUTTON,
                MOVE_COLUMN_RIGHT_TOOLTIP_BUTTON);
        buttonsPanel.add(moveRightButton);
        saveButton = new QButton(SAVE_REPORT_BUTTON,
                SAVE_REPORT_TOOLTIP_BUTTON);
        buttonsPanel.add(saveButton);
        loadButton = new QButton(LOAD_REPORT_BUTTON,
                LOAD_REPORT_TOOLTIP_BUTTON);
        buttonsPanel.add(loadButton);
        add(buttonsPanel);

        loadedReportLabel = new Label();
        loadedReportLabel.setText(REPORT_LOADED_LABEL + NONE_REPORT_NAME);
        add(loadedReportLabel);

        adhocGrid = new QGrid(new GridMeta(), false);
        DeckPanel deck = new DeckPanel();
        deck.add(adhocGrid.getView());
        deck.setWidth("100%");
        deck.showWidget(0);
        add(deck);

        Window.addWindowResizeListener(this);
        setWidth(StringUtil.pixelToSize(Window.getClientWidth()));
    }

    public Widget getView() {
        return this;
    }

    public void activated() {
        isActive = true;
        refresh();
    }

    public void disabled() {
        isActive = false;
    }

    /**
     * @return list of AdhocData elements. List<AdhocData>
     */
    public List getReportElements() {
        return reportElements;
    }

    public void onWindowResized(int width, int height) {
        setWidth(StringUtil.pixelToSize(width));
        setHeight(StringUtil.pixelToSize(height));
    }

    public void setWidth(String width) {
        super.setWidth(width);
        if(adhocGrid != null) {
            adhocGrid.getView().setWidth(width);
        }
    }

    public void setHeight(String height) {
        super.setHeight(height);
        if(adhocGrid != null) {
            int fullHeight = StringUtil.sizeToPixel(height);
            int gridHeight = fullHeight - loadedReportLabel.getOffsetHeight()
                    - buttonsPanel.getOffsetHeight()
                    - frameLinks.getOffsetHeight();
            if(gridHeight > 0) {
                adhocGrid.getView().setOffsetHeight(gridHeight);
            }
        }
    }

    private class PrintCallback extends RPC.QAsyncCallback {
        private String exportType;
        private long processId;
        private boolean printPage;

        public PrintCallback(String exportType, long processId,
                             boolean printPage) {
            this.exportType = exportType;
            this.processId = processId;
            this.printPage = printPage;
        }

        public void onRequestEnded(boolean success, Object result) {
            if(success) {
                JavaScriptObject printGridWindow = WindowHelper.openWindow(
                        "../getReport/response/" + exportType + "/"
                                + processId + "?transletName=report");
                if(printPage) {
                    WindowHelper.printWindow(printGridWindow);
                }
            }
        }
    }

    private class SaveReportCallback extends RPC.QAsyncCallback {
        public void onRequestEnded(boolean success, Object result) {
            if(success) {
                DialogHelper.showModalMessageDialog(
                        SUCCESSFULLY_SAVED_REPORT_MESSAGE);
            }
        }
    }

    private class SearchGridRecordsAsyncCallback extends RPC.QAsyncCallback {
        public void onRequestEnded(boolean success, Object result) {
            if(success) {
                SearchGridRecordsResponseObject searchRes
                        = (SearchGridRecordsResponseObject) result;
                QGridModel gridModel = adhocGrid.getModel();
                gridModel.setGridData(searchRes.getGridData(),
                        searchRes.getTotalRecordsCount(),
                        searchRes.getCurrentPage());
            }
        }
    }

    private class LoadReportCallback extends RPC.QAsyncCallback {
        public void onRequestEnded(boolean success, Object result) {
            if(success) {
                LoadReportResponseObject resp
                        = (LoadReportResponseObject) result;
                if(!StringUtil.isStringEmpty(resp.getWarningMessage())) {
                    DialogHelper.showMessageDialog(
                            REPORT_MAY_BE_INCORRECT_WARNING
                                    + resp.getWarningMessage());
                }
                Events.REPORT_LOADED.setData(result);
                getEventSource().fireEvent(Events.REPORT_LOADED);
            }
        }
    }
}
