/*
 * 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.controls.grid;

import com.google.gwt.user.client.ui.Widget;
import com.queplix.core.client.app.vo.GridMeta;
import com.queplix.core.client.app.vo.SortFieldImpl;
import com.queplix.core.client.app.vo.SubsetData;
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.grid.DataGrid;
import com.queplix.core.client.common.ui.grid.GridSelectionModListener;
import com.queplix.core.client.common.ui.grid.GridSortListener;
import com.queplix.core.client.common.ui.grid.SelectedRecord;
import com.queplix.core.client.common.ui.grid.SortColumn;
import com.queplix.core.client.common.ui.grid.SourcesGridSortEvents;
import com.queplix.core.client.i18n.I18N;

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

/**
 * This class responsible for the controller interface in QGrid component.
 */
class QGridControllerImpl implements QGridController,
        QPagerListener,
        GridSortListener,
        GridSelectionModListener,
        EventListener {

    private QGridModelImpl model;
    private QGridViewImpl view;

    private EventSource eventSource;

    /**
     * Construct grid controller object
     *
     * @param model model
     * @param view  view
     */
    public QGridControllerImpl(QGridModelImpl model, QGridViewImpl view) {
        this.model = model;
        this.view = view;
        eventSource = new EventSource(view);

        subscribeEvents();
    }

    public QGridModel getModel() {
        return model;
    }

    public QGridView getView() {
        return view;
    }

    private void subscribeEvents() {
        view.addPagerListener(this);
        view.addGridSortListener(this);
        view.addGridSelectionModListener(this);
        view.addEventListener(this);
    }

    public void clearSelectedRecord() {
        model.setSelectedRecordId(null);
        view.clearSelection();
    }

    protected void gridNeedData() {
        eventSource.fireEvent(Events.GRID_NEED_DATA);
    }

    public void onToggleCounter(boolean counterToggledOn) {
        model.setCounterToggledOn(counterToggledOn);
        gridNeedData();
    }

    public void onPageChange(long page) {
        if(model.getCurrentPage() != page) {
            model.setCurrentPage(page);
            gridNeedData();
        }
    }

    public void onPageSizeChange(int pageSize) {
        model.setPageSize(pageSize);
        gridNeedData();
    }

    public List getMarkedRecordsIds() {
        List selectedRows = view.getSelectedRows();
        List selectedRecordsIds = new ArrayList();
        for(int i = 0; i < selectedRows.size(); i++) {
            Integer integer = (Integer) selectedRows.get(i);
            selectedRecordsIds.add(model.getRecordIdByRow(integer.intValue()));
        }
        return selectedRecordsIds;
    }

    private void scrollGridToRow(int row) {
        view.scrollGridToRow(row);
    }

    public void onEvent(Event event, Widget sender) {
        Integer row = (Integer) event.getData();
        if(DataGrid.Events.GRID_ROW_SELECTED == event) {
            SelectedRecord data = new SelectedRecordImpl(model.getRecordIdByRow(
                    row.intValue()), model.getIncomingMetaData().getIndex());
            Events.RECORD_SELECTED.setData(data);
            getEventSource().fireEvent(Events.RECORD_SELECTED);
        } else if(DataGrid.Events.GRID_ROW_TO_BE_SELECTED == event) {
            Events.RECORD_TO_BE_SELECTED.setData(model.getRecordIdByRow(
                    row.intValue()));
            getEventSource().fireEvent(Events.RECORD_TO_BE_SELECTED);
        } else if(DataGrid.Events.SCROLL_TO_ROW == event) {
            scrollGridToRow(row.intValue());
        } else if(DataGrid.Events.COLUMN_SELECTED == event) {
            getEventSource().fireEvent(Events.GRID_COLUMN_SELECTED);
        } else if(DataGrid.Events.DELETE_KEY_PRESSED == event) {
            getEventSource().fireEvent(Events.DELETE_KEY_PRESSED);
        }
    }

    public void clearGrid() {
        clearSelectedRecord();
        model.setGridData(null);
        model.setSelectedRecordId(null);
    }

    public void onSort(SourcesGridSortEvents sender, SortColumn sortColumn) {
        GridMeta meta = model.getIncomingMetaData();
        int columnIndex = (int) meta.getColumns().getSelectedIDs()[sortColumn
                .getColumnIndex()];
        String columnID = meta.getFields()[columnIndex].getFieldID();
        SortFieldImpl sortField = model.getSortFieldImpl();
        sortField.setFieldID(columnID);
        sortField.setSortOrder(sortColumn.getAscending());

        gridNeedData();
    }

    public EventSource getEventSource() {
        return eventSource;
    }

    public void onCustomize(SubsetData data) {
        if((data != null) && (data.getSelectedIDs() != null) &&
                (data.getSelectedIDs().length > 0)) {
            Events.GRID_CUSTOMIZE.setData(data);
            eventSource.fireEvent(Events.GRID_CUSTOMIZE);
        } else {
            DialogHelper.showModalMessageDialog(
                    I18N.getMessages().atLeastOneColumnShouldBeSelected());
        }
    }

    public void onSelectAll() {
        view.selectAll();
    }

    public void onDeselectAll() {
        view.clearSelection();
    }

    public void onInvertSelection() {
        view.invertSelection();
    }

    public void onRefresh() {
        eventSource.fireEvent(QGridController.Events.GRID_REFRESH);
    }

    public void onPrint() {
        eventSource.fireEvent(QGridController.Events.GRID_PRINT);
    }

    public void onExportToWord() {
        eventSource.fireEvent(QGridController.Events.GRID_EXPORT_TO_WORD);
    }

    public void onExportToExcel() {
        eventSource.fireEvent(QGridController.Events.GRID_EXPORT_TO_EXCEL);
    }

    public void collectUISettings() {
        model.collectUISettings();
    }
}
