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

import com.google.gwt.user.client.ui.Widget;
import com.queplix.core.client.app.vo.FieldMeta;
import com.queplix.core.client.app.vo.FocusMeta;
import com.queplix.core.client.app.vo.GridData;
import com.queplix.core.client.app.vo.GridMeta;
import com.queplix.core.client.app.vo.MetaData;
import com.queplix.core.client.app.vo.RowData;
import com.queplix.core.client.app.vo.SavedSearchObject;
import com.queplix.core.client.app.vo.TextBoxFieldMeta;
import com.queplix.core.client.common.event.Event;
import com.queplix.core.client.common.event.EventListener;
import com.queplix.core.client.common.ui.ButtonData;
import com.queplix.core.client.common.ui.DialogHelper;
import com.queplix.core.client.common.ui.IconButton;
import com.queplix.core.client.common.ui.MenuPopup;
import com.queplix.core.client.common.ui.OkayCancelPopup;
import com.queplix.core.client.common.ui.grid.GridSelectionModListener;
import com.queplix.core.client.common.ui.grid.SelectedRecord;
import com.queplix.core.client.controls.grid.QGrid;
import com.queplix.core.client.controls.grid.QGridController;
import com.queplix.core.client.i18n.I18N;


/**
 * A box with saved searches list
 *
 * @author Vasily Mikhailitchenko
 * @since 19 Feb 2007
 */
class LoadSearchBox extends OkayCancelPopup implements EventListener {
    public static final int MIN_HEIGHT = 108;
    public static final int MIN_WIDTH = 335;

    private EventListener commonEventsListener;
    private EventListener menuEventListener;
    private MetaData appMetaData;

    public static interface Events {
        Event/*]<Long>[*/ DELETE_SAVED_SEARCH = new Event();
        Event/*]<SavedSearchObject>[*/ DO_LOAD_SAVED_SEARCH = new Event();
        Event DELETE_ACTION = new Event(); // internal
    }

    private QGrid grid;
    private GridData gd = new GridData();
    private SavedSearch savedSearch;
    private String selectedSearchName;
    private Long selectedRecordID;

    public LoadSearchBox(String caption, SavedSearch savedSearch,
                         MetaData appMetaData) {
        super(caption, true);
        grid = new QGrid(new GridMeta(new FieldMeta[]{
                new TextBoxFieldMeta("1", I18N.getMessages().searchName())
                ,
                new TextBoxFieldMeta("2", I18N.getMessages().focus())
        }, new long[]{
                0,
                1
        }), true, false, false, false, true);

        this.savedSearch = savedSearch;
        this.selectedSearchName = null;
        this.appMetaData = appMetaData;

        IconButton ib = new IconButton(new ButtonData(
                I18N.getMessages().delete()));
        MenuPopup menu = grid.getView().getMenu();
        menu.addButton(Events.DELETE_ACTION, ib.getButtonState());

        initEventListeners();

        menu.getEventSource().addEventListener(menuEventListener);
        grid.getController().getEventSource().addEventListener(
                commonEventsListener);
        this.setWidget(grid.getView());
        this.setMinSize(MIN_WIDTH, MIN_HEIGHT);
        getEventSource().addEventListener(commonEventsListener);
    }

    private void refreshDataGrid() {
        selectedSearchName = null;
        selectedRecordID = null;
        SavedSearchObject[] savedSearches = savedSearch.getSavedSearches();
        gd = new GridData();
        for(int i = 0; i < savedSearches.length; i++) {
            SavedSearchObject searchObject = savedSearches[i];
            String searchName = searchObject.getSearchName();
            String formId = searchObject.getFormId();
            FocusMeta.Index focusIndex = appMetaData.getIndexByID(formId);
            String focusName = appMetaData.getFocuses()[focusIndex.focus]
                    .getCaption();
            gd.insertRow(new RowData(new Long(i), new String[]{
                    searchName,
                    focusName
            }));
        }
        ((GridSelectionModListener) grid.getController()).onDeselectAll();
        grid.getModel().setGridData(gd);
    }

    public void onRefresh() {
        refreshDataGrid();
    }

    private void initEventListeners() {
        commonEventsListener = new EventListener() {
            public void onEvent(Event event, Widget sender) {
                if(OkayCancelPopup.Events.OK.equals(event)) {
                    if(selectedSearchName != null) {
                        Events.DO_LOAD_SAVED_SEARCH.setData(
                                savedSearch.loadSearch(selectedSearchName));
                        getEventSource().fireEvent(Events.DO_LOAD_SAVED_SEARCH);
                        hide();
                    }
                } else if(OkayCancelPopup.Events.CANCEL.equals(event)) {
                    hide();
                } else if(QGridController.Events.RECORD_SELECTED.equals(
                        event)) {
                    Long selectedRow = ((SelectedRecord) 
                         QGridController.Events.RECORD_SELECTED
                        .getData()).getRecordId();
                    SavedSearchObject[] savedSearches = savedSearch
                            .getSavedSearches();
                    SavedSearchObject searchObject = savedSearches[selectedRow
                            .intValue()];
                    selectedRecordID = searchObject.getRowID();
                    selectedSearchName = searchObject.getSearchName();
                }
            }
        };

        menuEventListener = new EventListener() {
            public void onEvent(Event event, Widget sender) {
                if(Events.DELETE_ACTION.equals(event)) {
                    if(selectedRecordID != null) {
                        int answer = DialogHelper.showModalQuestionDialog(
                                I18N.getMessages().deleteSearchItem());
                        if(answer == DialogHelper.YES) {
                            Events.DELETE_SAVED_SEARCH.setData(
                                    selectedRecordID);
                            getEventSource().fireEvent(
                                    Events.DELETE_SAVED_SEARCH);
                        }
                    }
                }
            }
        };
    }

    public String getName() {
        return selectedSearchName;
    }
}
