﻿// see http://www.extjs.com/products/extcore/manual/content/classsystem.html for more info
// ----------- content panel helper wrapper class ----------- //
Ext.ux.GridContentPanelHelper = Ext.extend(Ext.ux.ContentPanelHelper, {

    // internal fields
    m_currentTabId: "",
    m_gridPanel: null,
    m_pagingBar: null,
    m_store: null,

    m_deviceId: g_cloud_deviceId,

    m_query: "",


    // external delegates
    m_getDeviceIdDelegate: null,

    // delegate setters
    setGetDeviceIdDelegate: function(theDelegate) {
        this.m_getDeviceIdDelegate = theDelegate;
    },


    // standard constructor
    constructor: function(
        contentElementId, footerElementId,
        pagingBarId, pagingHtmlElement,
        renderTemp, renderTarget,
        defaultSortField,
        footerCaption,
        playSmallInactiveImageUrl, playSmallHoverImageUrl,
        playWarningSmallInactiveImageUrl, playWarningSmallHoverImageUrl,
        dragDropGroups, dragDropGroup,
        gridPanelType) {

        // args passed in
        this.m_pagingBarId = pagingBarId;
        this.m_pagingHtmlElement = pagingHtmlElement;
        this.m_renderTemp = renderTemp;
        this.m_renderTarget = renderTarget;
        this.m_defaultSortField = defaultSortField;
        this.m_footerCaption = footerCaption;
        this.m_playSmallInactiveImageUrl = playSmallInactiveImageUrl;
        this.m_playSmallHoverImageUrl = playSmallHoverImageUrl;
        this.m_playWarningSmallInactiveImageUrl = playWarningSmallInactiveImageUrl;
        this.m_playWarningSmallHoverImageUrl = playWarningSmallHoverImageUrl;
        this.m_dragDropGroups = dragDropGroups;
        this.m_dragDropGroup = dragDropGroup;
        this.m_gridPanelType = gridPanelType;

        Ext.ux.GridContentPanelHelper.superclass.constructor.call(this, contentElementId, footerElementId, null);
    },

    // standard initializer
    initComponent: function() {
        Ext.ux.GridContentPanelHelper.superclass.initComponent.apply(this, arguments);

        // extra args have to go here as base class initComponent doesn't get called for some reason
        var config = {};

        Ext.apply(this, config);
        Ext.apply(this.initialConfig, config);

        // add custom events
        this.addEvents(g_customEvent_gridContentPanelHelper_rowClick);
        this.addEvents(g_customEvent_gridContentPanelHelper_rowDblClick);
        this.addEvents(g_customEvent_gridContentPanelHelper_emptySpaceClick);
        this.addEvents(g_customEvent_gridContentPanelHelper_emptySpaceDblClick);
    },

    // initialization
    initialize: function(tabs) {
        Ext.ux.GridContentPanelHelper.superclass.initialize(tabs, delegate(this, this.handleTabClick));
    },

    // get current device id
    getDeviceId: function() {
        return this.m_deviceId;
    },

    // gets the current query
    getQuery: function() {
        return this.m_query;
    },

    // do the search click logic
    doSearchClick: function() {
        this.loadData();
    },

    // get the current record id
    getCurrentRecordId: function() {
        var recordId = g_default_xPOPropertyId;
        
        if (this.m_gridPanel !== null) {
            recordId = this.m_gridPanel.getCurrentRecordId();
        }
        return recordId;
    },

    // do the reset click logic
    doResetClick: function() {

        // reset search
        this.setSearchParams("");

        // clear the grid
        if (this.m_store) {
            this.m_store.removeAll();

            // set the totalLength to 0 as it doesn't get cleared when
            // changing the store content locally (by design apparently)
            this.m_store.totalLength = 0;
        }

        // update the scrollbar
        if (this.m_gridPanel) {
            this.m_gridPanel.updateScrollbar();
        }

        // update the footer
        if (this.m_pagingBar) {
            this.m_pagingBar.updateInfo();
        }
    },

    // do the tab click logic
    doTabClick: function(newTabId, forceRefresh) {

        // call external delegate
        if (this.m_getDeviceIdDelegate) {
            this.m_deviceId = this.m_getDeviceIdDelegate();
        }

        var tabClickParams = {
            id: this.getDeviceId(),
            query: this.getQuery()
        };
        this.setTabClickParams(tabClickParams);

        // call base class
        Ext.ux.GridContentPanelHelper.superclass.doTabClick.call(this, newTabId, forceRefresh);
    },

    // do any additional tab click bits and pieces
    doTabClickEx: function() {

        // reset grids
        this.m_gridPanel = null;
    },

    // set the search params
    setSearchParams: function(query) {
        this.m_query = query;
    },

    // single grid configuration
    configureSingleGrid: function(tabData) {

        var params = {
            id: this.getDeviceId(),
            query: this.getQuery()
        };

        this.loadSingle_singleGridData(tabData.additionalUrls[0], params);

        this.m_gridPanel.configureDragDrop(this.m_dragDropGroup);
    },

    // configure grid drag/drop
    configureSingleDragDrop: function() {
        var ddAddGroups = this.m_dragDropGroups;

        if (this.m_gridPanel !== null) {
            if (this.m_gridPanel.getView().dragZone !== null) {
                this.m_gridPanel.getView().dragZone.isTarget = true;
            }

            this.m_gridPanel.setDdAddGroups(ddAddGroups);
        }
    },

    // single grid footer configuration
    configureSingleGridFooter: function(tabData) {
    },

    // load data into the grid
    loadSingle_singleGridData: function(url, params) {

        this.m_store = extJsStore_createStore(
                this.m_store,
                url,
                this.m_defaultSortField,
                g_extjsGrid_defaultSortDirection,
                params);

        this.m_pagingBar = extJsPagingBar_createPagingBar(
                this.m_pagingBar,
                this.m_pagingBarId,
                this.m_pagingHtmlElement,
                this.m_store,
                this.m_footerCaption);

        // create new gridPanel if necessary
        if (this.m_gridPanel === null) {

            var args = {
                store: this.m_store,
                autoHeight: true,
                enableDragDrop: true,
                renderTemp: this.m_renderTemp,
                renderTarget: this.m_renderTarget, // don't have to call render() if we set this
                dragDropHighlightType: g_dragDropHighlightType_row,
                playSmallInactiveImageUrl: this.m_playSmallInactiveImageUrl,
                playSmallHoverImageUrl: this.m_playSmallHoverImageUrl,
                playWarningSmallInactiveImageUrl: this.m_playWarningSmallInactiveImageUrl,
                playWarningSmallHoverImageUrl: this.m_playWarningSmallHoverImageUrl
            };

            // create a new instance of the specified type
            this.m_gridPanel = new this.m_gridPanelType(Ext.apply(args));

            extJsStore_hookUpStoreEventHandlers(this.m_store);
            extJsGrid_hookUpStoreEventHandlers(this.m_gridPanel, this.m_store);

            // hook up double-click listeners (pass 'this' in as scope)
            this.m_gridPanel.on('rowclick', this.gridRowClick, this);
            this.m_gridPanel.on('rowdblclick', this.gridRowDblClick, this);
            this.m_gridPanel.on('click', this.gridClick, this);
            this.m_gridPanel.on('dblclick', this.gridDblClick, this);
        }

        extJsStore_loadData(this.m_store, this.loadSingle_singleGridDataSuccess, this);
    },

    // callback called after store has loaded grid data
    loadSingle_singleGridDataSuccess: function(r, options, success) {
        if (r.length === 0) {
            // display warning message
        }
        else {
            // display grid / hide message
        }

        // show the footer
        this.showFooter(true);
    },

    // grid row single-click handler
    gridRowClick: function(grid, rowIndex, e) {
        this.m_gridPanel.setCurrentRowIndex(rowIndex);
        var record = this.m_gridPanel.getCurrentRecord();

        // fire row click event
        this.fireEvent(g_customEvent_gridContentPanelHelper_rowClick, record.data.id);
    },

    // grid row double-click handler
    gridRowDblClick: function(grid, rowIndex, e) {
        this.m_gridPanel.setCurrentRowIndex(rowIndex);
        var record = this.m_gridPanel.getCurrentRecord();

        // fire click event
        this.fireEvent(g_customEvent_gridContentPanelHelper_rowDblClick, record.data.id, record.data.name);
    },

    // grid click handler
    gridClick: function(e) {
        var selections = this.m_gridPanel.getSelectionModel().getSelections();
        if ((selections === false) || (selections.length === 0)) {

            // fire empty space click event
            this.fireEvent(g_customEvent_gridContentPanelHelper_emptySpaceClick);
        }
    },

    // grid double-click handler
    gridDblClick: function(e) {
        var selections = this.m_gridPanel.getSelectionModel().getSelections();
        if ((selections === false) || (selections.length === 0)) {

            // fire empty space double-click event
            this.fireEvent(g_customEvent_gridContentPanelHelper_emptySpaceDblClick);
        }
    },

    // clears the selection in the grid
    clearSelection: function() {
        this.m_gridPanel.clearSelection();
    },
    
    // clear the current row index (and update the highlighting);
    clearCurrent: function() {
        this.m_gridPanel.setCurrentRowIndex(g_default_xPOPropertyId);
        this.m_gridPanel.autoHighlightCurrentRow();
    },

    // refresh the visible grid
    refresh: function() {
        if (this.m_gridPanel !== null) {
            this.m_gridPanel.getView().refresh(true);
        }
    },

    // reload data in the grid
    reload: function() {
        if (this.m_gridPanel !== null) {
            this.m_gridPanel.reload();
        }
    },

    // retrieve the ids of the selected items
    getSelectedIds: function() {
        var aSelectedIds = [];

        if (this.m_gridPanel) {
            var selections = this.m_gridPanel.getSelectionModel().getSelections();
            if (selections) {
                for (var iSelection = 0; iSelection < selections.length; iSelection++) {
                    aSelectedIds.push(selections[iSelection].data.id);
                }
            }
        }

        return aSelectedIds;
    },

    // retrieve the ids of the selected items
    getSelectedId: function() {
        var aSelectedIds = [];

        if (this.m_gridPanel) {
            var selections = this.m_gridPanel.getSelectionModel().getSelections();
            if (selections && selections.length == 1) {
                selections[0].data.id;
            }
            else {
                return -1;
            }
        }
        return aSelectedIds;
    }
});