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

import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Command;
import com.queplix.core.client.app.vo.FieldMeta;
import com.queplix.core.client.app.vo.FieldOnDemandData;
import com.queplix.core.client.app.vo.FormButtonMeta;
import com.queplix.core.client.app.vo.FormMeta;
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.RecordFilter;
import com.queplix.core.client.app.vo.RowData;
import com.queplix.core.client.common.CollectionsHelper;
import com.queplix.core.client.common.StringUtil;
import com.queplix.core.client.common.event.Event;
import com.queplix.core.client.common.event.EventSource;
import com.queplix.core.client.common.ui.OkayCancelPopup;
import com.queplix.core.client.common.ui.WindowHelper;
import com.queplix.core.client.common.ui.SplittedPanel;
import com.queplix.core.client.common.ui.resizable.ResizableScrollPanel;
import com.queplix.core.client.controls.form.QForm;
import com.queplix.core.client.controls.form.QFormController;
import com.queplix.core.client.controls.form.QFormLayout;
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 java.util.List;

/**
 * This class responsible for creating sets of filters for the inner entity in
 * in-form grid control. Finally should return
 * {@link com.queplix.core.client.app.vo.RecordFilter} object.
 *
 * @author Sergey Kozmin
 * @since 03.04.2007
 */
class FilteringDialog extends OkayCancelPopup {
    private static final int DEFAULT_HEIGHT = 250;
    private static final int DEFAULT_WIDTH = 600;

    private QGrid grid;
    private QForm form;
    private SplittedPanel splittedPanel;
    private ResizableScrollPanel formRSP;

    public FilteringDialog(String caption, GridMeta filteringGrid,
                           FormMeta filteringForm) {
        super(caption);
        initGUI(filteringGrid, filteringForm);
        splittedPanel.setSize(DEFAULT_WIDTH + "px", DEFAULT_HEIGHT + "px");
    }

    private void initGUI(GridMeta filteringGrid, FormMeta formMeta) {
        grid = new QGrid(filteringGrid, true, false, false, false, true);       

        if(formMeta.getLayoutMeta() == null) {
            FieldMeta[] fieldMetas = formMeta.getEntityMeta().getFields();
            int formWidth = 2;

            formMeta.setButtons(getSearchAndClearIfAny(formMeta.getButtons()));

            form = new QForm(formMeta, formWidth, (int) Math.ceil(
                    fieldMetas.length / (float) formWidth),
                    QFormLayout.HORIZONTAL_FLOW_LAYOUT, false, false);
        } else {
            form = new QForm(formMeta, false, false);
        }

        form.getFormController().getEventSource().addEventListener(this);
        grid.getController().getEventSource().addEventListener(this);

        formRSP = new ResizableScrollPanel(form.getView());
        DOM.setStyleAttribute(formRSP.getElement(), "overflow", "hidden");

        splittedPanel = new SplittedPanel(grid.getView(), formRSP, 60, SplittedPanel.VERTICAL);
        setWidget(splittedPanel);        
        form.getView().setSelected(true);

        WindowHelper.disableSelection(grid.getView().getElement());

        // onLoad and onAttach don't toggle for popup
        DeferredCommand.add(new Command(){
            public void execute() {
                splittedPanel.setMinHeight(formRSP, form.getView().getOffsetHeight() + 16);
                int formWidth = form.getView().getOffsetWidth();
                if(formWidth > splittedPanel.getOffsetWidth()) {
                    splittedPanel.setOffsetWidth(formWidth);
                }
                grid.getView().setOffsetWidth(formWidth);
                setMinSize(formWidth, DEFAULT_HEIGHT);
            }
        });
    }

    private FormButtonMeta[] getSearchAndClearIfAny(FormButtonMeta[] buttons) {
        FormButtonMeta searchBtn = null;
        FormButtonMeta clearBtn = null;
        for(int i = 0; i < buttons.length; i++) {
            if(QFormController.FORM_SEARCH_BUTTON.equalsIgnoreCase(
                    buttons[i].getId())) {
                searchBtn = buttons[i];
            } else if(QFormController.FORM_CLEAR_BUTTON.equalsIgnoreCase(
                    buttons[i].getId())) {
                clearBtn = buttons[i];
            }
        }
        int len = ((searchBtn == null) ? 0:1) + ((clearBtn == null) ? 0:1);
        FormButtonMeta[] formButtonMetas = new FormButtonMeta[len];

        if(clearBtn != null) {
            formButtonMetas[--len] = clearBtn;
        }
        if(searchBtn != null) {
            formButtonMetas[--len] = searchBtn;
        }
        return formButtonMetas;
    }

    public void reset() {
        grid.getController().clearGrid();
        form.getFormController().clearForm();
    }

    public void setGridData(List data, int currentPage, int totalRecordsCount) {
        RowData[] array = new RowData[data.size()];
        CollectionsHelper.copyToArray(data, array);
        QGridModel qGridModel = grid.getModel();
        qGridModel.setGridData(new GridData(array, ""), totalRecordsCount,
                currentPage);
    }

    public RecordFilter getDialogFilter() {
        List markedRows = grid.getController().getMarkedRecordsIds();
        RecordFilter filter;
        if(markedRows.size() > 0) {
            filter = RecordFilter.createRecordsFilter(markedRows);
        } else {
            List nonEmptyFilters = form.getModel().getNonEmptyFilters();
            filter = RecordFilter.createFieldsFilter(nonEmptyFilters);
        }
        return filter;
    }

    public GridSearchProperties getGridProperties() {
        QGridModel gridModel = grid.getModel();
        return new GridSearchProperties(
                gridModel.isCounterToggledOn(),
                (int) gridModel.getCurrentPage(),
                gridModel.getPageSize(),
                gridModel.getSortField());
    }

    public void setFieldOnDemandData(FieldOnDemandData data) {
        form.getModel().setOnDemandDataForElement(data);
    }

    public void onEvent(Event event, Widget sender) {
        if(sender == this) {//handle popup events
            if(OkayCancelPopup.Events.OK == event
                    || OkayCancelPopup.Events.CANCEL == event) {
                super.onEvent(event, sender);
                filteringEventSource.fireEvent(
                        event);//redirect OK and CANCEL events
            }
        } else if(sender == form.getView()) {//handle form events
            if(QFormController.Events.FORM_SEARCH_BUTTON_EVENT == event ||
                    QFormController.Events.FORM_CONTROL_NEED_MORE_DATA_EVENT
                            == event) {
                filteringEventSource.fireEvent(event);
            } else if(QFormController.Events.FORM_CLEAR_BUTTON_EVENT == event) {
                reset();
            }
        } else if(sender == grid.getView()) {
            if(QGridController.Events.GRID_NEED_DATA == event) {
                filteringEventSource.fireEvent(event);
            }
        }
    }

    // -------------------- public events ------------------------
    public EventSource getFilteringEventSource() {
        return filteringEventSource;
    }

    private EventSource filteringEventSource = new EventSource(this);

    public static interface Events extends OkayCancelPopup.Events {
        Event/*]<FieldDataRequest>[*/ FORM_CONTROL_NEED_MORE_DATA_EVENT
                = QFormController.Events.FORM_CONTROL_NEED_MORE_DATA_EVENT;

        Event FORM_SEARCH_BUTTON_EVENT
                = QFormController.Events.FORM_SEARCH_BUTTON_EVENT;

        Event GRID_NEED_DATA = QGridController.Events.GRID_NEED_DATA;
    }
    // ----------------- end of public events --------------------
}
