/*
 * 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.user.client.ui.ClickListener;
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.AdhocDeleteReportRequest;
import com.queplix.core.client.app.vo.BaseGridRequest;
import com.queplix.core.client.app.vo.EntityIDRequestObject;
import com.queplix.core.client.app.vo.GridData;
import com.queplix.core.client.app.vo.GridMeta;
import com.queplix.core.client.app.vo.GridSearchProperties;
import com.queplix.core.client.app.vo.SearchGridRecordsResponseObject;
import com.queplix.core.client.common.event.Event;
import com.queplix.core.client.common.event.EventListener;
import com.queplix.core.client.common.ui.OkayCancelPopup;
import com.queplix.core.client.common.ui.grid.SelectedRecord;
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.i18n.I18N;

/**
 * Class handles all the load reports dialog behaviors
 *
 * @author Sergey Kozmin
 * @since 13.02.2007
 */
public class LoadingReportDialog extends OkayCancelPopup
        implements EventListener {
    private static final String DIALOG_TITLE = I18N.getMessages()
            .adhocLoadReportDialogTitle();
    private static final String AVAILABLE_REPORTS_LABEL_TITLE = I18N
            .getMessages().adhocAvailableReportsLabel();
    private static final String DELETE_BUTTON_LABEL = I18N.getMessages()
            .adhocdDeleteReportButton();
    private static final String DELETE_BUTTON_TOOLTIP = I18N.getMessages()
            .adhocdDeleteReportButtonTooltip();

    private static final int UNSELECTED_RECORD = -1;

    private RPC.QAsyncCallback callback;
    /**
     * Currently selected record in loadReportPopup. After dialog is shown value is equals #UNSELECTED_RECORD,
     * until user select some grid recod.
     */
    private long loadReportIndex = UNSELECTED_RECORD;
    /**
     * Reports list grid.
     */
    private QGrid reportsListGrid;
    private QButton deleteReportBtn;

    /**
     * Construct the object
     *
     * @param adhocReportsMeta grid meta for reports grid
     * @param callback         callback object for record selection
     */
    public LoadingReportDialog(GridMeta adhocReportsMeta,
                               RPC.QAsyncCallback callback) {
        super(DIALOG_TITLE);
        this.callback = callback;
        initGUI(adhocReportsMeta);
    }

    private void initGUI(GridMeta adhocReportsMeta) {
        VerticalPanel mainPanel = new VerticalPanel();

        mainPanel.add(createActionButtonPanel());
        mainPanel.add(new Label(AVAILABLE_REPORTS_LABEL_TITLE));

        reportsListGrid = new QGrid(adhocReportsMeta, true);
        mainPanel.add(reportsListGrid.getView());
        reportsListGrid.getController().getEventSource().addEventListener(this);
        setWidget(mainPanel);
    }

    private Widget createActionButtonPanel() {
        HorizontalPanel buttonsPanel = new HorizontalPanel();
        deleteReportBtn = new QButton(DELETE_BUTTON_LABEL,
                DELETE_BUTTON_TOOLTIP);
        buttonsPanel.add(deleteReportBtn);
        deleteReportBtn.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                deleteReport();
            }
        });
        return buttonsPanel;
    }

    private void deleteReport() {
        RPC.QAsyncCallback callback = new RepotsListCallback();
        QGridModel gridModel = reportsListGrid.getModel();
        GridSearchProperties props = new GridSearchProperties(
                gridModel.isCounterToggledOn(),
                (int) gridModel.getCurrentPage(),
                gridModel.getPageSize(),
                gridModel.getSortField());
        AdhocDeleteReportRequest request = new AdhocDeleteReportRequest(props,
                new Long(loadReportIndex));
        RPC.getRPC().deleteReport(request, callback);
    }

    private void refreshButtons() {
        deleteReportBtn.setEnabled(loadReportIndex != UNSELECTED_RECORD);
    }

    public void showReportList() {
        RPC.QAsyncCallback callback = new RepotsListCallback();
        QGridModel gridModel = reportsListGrid.getModel();
        GridSearchProperties props = new GridSearchProperties(
                gridModel.isCounterToggledOn(),
                (int) gridModel.getCurrentPage(),
                gridModel.getPageSize(),
                gridModel.getSortField());
        BaseGridRequest gridRequest = new BaseGridRequest(props);
        RPC.getRPC().loadReports(gridRequest, callback);
    }

    private void setGridData(GridData data, int currentPage,
                             int totalRecordsCount) {
        QGridModel gridModel = reportsListGrid.getModel();
        gridModel.setGridData(data, totalRecordsCount, currentPage);
    }

    public void onEvent(Event event, Widget sender) {
        if(event == OkayCancelPopup.Events.OK) {
            if(loadReportIndex != UNSELECTED_RECORD) {
                EntityIDRequestObject request = new EntityIDRequestObject("",
                        new Long(loadReportIndex));
                RPC.getRPC().loadReport(request, callback);
            }
            hide();
        } else if(event == OkayCancelPopup.Events.CANCEL) {
            hide();
        } else if(event == QGridController.Events.RECORD_SELECTED) {
            Long recordID = ((SelectedRecord) QGridController.
                Events.RECORD_SELECTED.getData()).getRecordId();
            loadReportIndex = recordID.longValue();
            refreshButtons();
        } else if(event == QGridController.Events.GRID_REFRESH
                || event == QGridController.Events.GRID_NEED_DATA) {
            showReportList();
        }
    }

    public void show() {
        loadReportIndex = UNSELECTED_RECORD;
        refreshButtons();
        super.show();
    }

    private class RepotsListCallback extends RPC.QAsyncCallback {
        public void onRequestEnded(boolean success, Object result) {
            if(success) {
                SearchGridRecordsResponseObject searchResp
                        = (SearchGridRecordsResponseObject) result;
                setGridData(searchResp.getGridData(),
                        searchResp.getCurrentPage(),
                        searchResp.getTotalRecordsCount());
                loadReportIndex = UNSELECTED_RECORD;
                refreshButtons();
                if(!isDialogShown()) {
                    show();
                }
            }
        }
    }
}
