/*
 * 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.SourcesTabEvents;
import com.google.gwt.user.client.ui.TabListener;
import com.queplix.core.client.app.Application;
import com.queplix.core.client.app.vo.FamgMeta;
import com.queplix.core.client.app.vo.FormMeta;
import com.queplix.core.client.app.vo.GridMeta;
import com.queplix.core.client.app.vo.TabMeta;
import com.queplix.core.client.common.event.EventSource;
import com.queplix.core.client.common.ui.QTabPanel;
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;

/**
 * Postfix GA - Grid Area.
 * On tab(of QTabPanel) change you should select corresponding QGrid in this class to show correct contents.
 * Class MainFrameGA contains array of FocusGA.
 * Class FocusGA contains array of SubFocusGA.
 * Class SubFocusGA contains array of TabGA.
 * Class TabGA contains array of QGrid.
 *
 * @author Aliaksandr Melnik
 * @since 19 October 2006
 */
class TabGA extends QTabPanel {

    // -------------------- public events ------------------------
    public static interface Events extends QGridController.Events {
    }

    private EventSource eventSource = new EventSource(this);

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

    private boolean[] initializedTabs;
    private QGrid[] grids;
    private FormMeta[] formsMeta;
    private GridMeta[] gridsMeta;
    private FamgMeta[] famgsMeta;

    private int activeForm = -1;

    public TabGA(TabMeta tabMeta) {
        super(TAB_LAYOUT_VERTICAL);
        this.getTabBar().setStyleName("grid-TabBar");
        String status = Application.getStatus();

        famgsMeta = tabMeta.getFamgs();
        formsMeta = new FormMeta[famgsMeta.length];
        gridsMeta = new GridMeta[famgsMeta.length];
        for(int i = 0; i < famgsMeta.length; i++) {
            formsMeta[i] = famgsMeta[i].getForm();
            gridsMeta[i] = famgsMeta[i].getGrid();
        }
        initializedTabs = new boolean[famgsMeta.length];
        grids = new QGrid[famgsMeta.length];

        int cardsCount = 0;
        for(int i = 0; i < formsMeta.length; i++) {
            if (formsMeta[i].isVisible()) {
                addCard(formsMeta[i].getCaption());
                cardsCount++;
            }
        }

        if(cardsCount > 0) {
            selectTab(0);
        }

        addTabListener(new TabListener() {
            public boolean onBeforeTabSelected(SourcesTabEvents sender,
                                               int index) {
                initTab(index);
                return true;
            }

            public void onTabSelected(SourcesTabEvents sender, int index) {
            }
        });
        grids[0].getView().setVisible(true);
    }

    public QGrid[] getGrids() {
        return grids;
    }

    public void selectTab(int index) {
        initTab(index);
        super.selectTab(index);
    }

    /**
     * Initialize the given tab
     *
     * @param index tab index to initialize
     */
    private void initTab(int index) {
        activeForm = index;
        if(!initializedTabs[index]) {
            initGrid(index);
            QGridView nextGridView = grids[index].getView();
            remove(index);
            insert(nextGridView, formsMeta[index].getCaption(), index);
            initializedTabs[index] = true;
        }
    }

    /**
     * Initialize the given grid
     *
     * @param index grid index to initialize
     */
    private void initGrid(int index) {
        if(grids[index] == null) {
            grids[index] = new QGrid(gridsMeta[index], false, true, true, true,
                    true);
            grids[index].getController().getEventSource().addEventListener(
                    eventSource); // retranslate events
        }
    }

    public void performCommand(GridCommand command, int gridIndex) {
        switch(command.getCommandID()) {
            case GridCommand.SET_ROW_DATA: {
                //if we haven't element with equal id, we insert it to model.
                initGrid(gridIndex);
                QGridModel gridModel = grids[gridIndex].getModel();
                gridModel.setRowData(
                        ((SetDataForRowCommand) command).getData());
                break;
            }
            case GridCommand.SET_GRID_DATA: {
                SetDataForGridCommand sdfgc = (SetDataForGridCommand) command;
                initGrid(gridIndex);
                QGridModel gridModel = grids[gridIndex].getModel();
                gridModel.setGridData(sdfgc.getData(),
                        sdfgc.getTotalRecordsCount(), sdfgc.getCurrentPage());
                break;
            }
            case GridCommand.CLEAR_SELECTED_RECORD: {
                if(grids[gridIndex] != null) {
                    grids[gridIndex].getController().clearSelectedRecord();
                }
                break;
            }
            default: {
                //other events not implemented yet.
            }
        }
    }

    void activateGrid(FamgMeta.Index index) {
        selectTab(index.famg);
    }

    public FamgMeta.Index getSelectedFormIndex() {
        if(activeForm == -1) {
            return null;
        } else {
            return famgsMeta[activeForm].getIndex();
        }
    }

    public void clearAllGrids() {
        for(int i = 0; i < grids.length; i++) {
            if(grids[i] != null) {
                grids[i].getController().clearGrid();
            }
        }
    }

    QGrid getGrid(FamgMeta.Index famgIndex) {
        return grids[famgIndex.famg];
    }

    FamgMeta.Index getActiveGridIndex() {
        FamgMeta.Index index = new FamgMeta.Index();
        index.famg = activeForm;
        return index;
    }

    void collectUISettings() {
        for(int i = 0; i < grids.length; i++) {
            if(grids[i] != null) {
                grids[i].getController().collectUISettings();
            }
        }
    }
}
