/*  PagingToolbar */    

Veeam.PagingToolbar = Ext.extend(Ext.PagingToolbar, {
    constructor: function(config){
        Veeam.PagingToolbar.superclass.constructor.call(this, config);
    }, 
    lastCommand : '',
    onClick : function(which) { 
        this.lastCommand = which;
        Veeam.PagingToolbar.superclass.onClick.apply( this, arguments );
    }
});

/* GridView */
Veeam.GridView = Ext.extend(Ext.grid.GridView, {
    constuctor: function(config){
        GridView.superclass.constructor.call(this, config);
    },
    scrollTop : function() {
        this.scroller.dom.scrollTop = 0;
        this.scroller.dom.scrollLeft = 0;
    },
    refresh : function() {
        Veeam.GridView.superclass.refresh.apply(this, arguments );
    }
});

/* TaskButton*/    
Veeam.TaskButton = Ext.extend( Ext.Toolbar.Button, {
    constructor: function(config){
        config = Ext.apply( {} , config||{} , {
            minWidth: 75,
            disabled: true
        });
        Veeam.TaskButton.superclass.constructor.apply( this, [config] );
    }
});

Ext.reg('vm.ui.taskbutton', Veeam.TaskButton);

/* AutoGridPanel */
Veeam.AutoGridPanel = function(config) {
    
    this.gridConfig = config;
    this.createGrid( config );
    this.createDetails( config );
    this.createHeader( config );
    this.initPlugins( config );

    var items = [this.grid];
    if ( this.details ) items[items.length] = this.details;
    if ( this.northHeader ) items[items.length] = this.northHeader;
    
    config = Ext.applyIf( config, { 
        items:items, 
        id: config.gridId || Ext.id(null, 'autogrid-'),
        tbar: this.gridToolBar,
        layout:'border',
        frame: true,
        cls: 'x-veeam-grid',
        listeners: { resize : this.resizeHandler.createDelegate(this) },
        border: true });
    
    Veeam.AutoGridPanel.superclass.constructor.apply(this, [config]);
};

Ext.extend( Veeam.AutoGridPanel, Ext.Panel, {
    destroy: function() {
        if ( this.elHeaderLink ) this.elHeaderLink.remove();
        
        this.grid.destroy();
        Veeam.AutoGridPanel.superclass.destroy.call(this); //TODO. why https warnings?
        
        delete this.store;
        delete this.grid;
    },
    
    render: function() {
        if ( this.gridPagingBar )
            this.gridPagingBar.pageSize = this.calcPageSize();
        Veeam.AutoGridPanel.superclass.render.apply(this, arguments);

    },
    
    initPlugins: function(cfg){
        var plugins = [];
        if (cfg.plugins) {
            var pns = cfg.plugins;
            if (!Ext.isArray(pns)) {
                pns = [ cfg.plugins ];
            } 
            
            Ext.each(pns, function(item, i){
                if (typeof item == 'string'){
                     //  Create new instance of plugin
                     try {
                        var plugin = Veeam.ObjectHelper.create(item);
                        plugins.push( plugin );   
                    } catch (e) {
                        Veeam.Msg.error({ msg: "Failed to initailize plugin " + item });  
                     }
                }
            }, this);
        
            delete cfg.plugins;
            
            cfg.plugins = plugins;
        }    
        
    },
    
    
    createHeader : function(config) {
        if ( !config.northHeader ) return;

        this.northHeader = new Ext.BoxComponent({
            cls: 'reports-job-info-panel reports-job-info-panel-body',
            split: false,
            region: 'north',
            autoHeight: true,
            boxMinHeight: 100,
            listeners: { render: this.renderHeader.createDelegate(this) }
        });
    },
    
    renderHeader : function(c) {
        var hcfg = this.initialConfig.northHeader;
        var el = c.el.insertHtml('afterBegin', hcfg.html, true );
        if ( hcfg.token ) {
            this.elHeaderLink = c.el.child('a');
            this.elHeaderLink.setVisible(true);
            this.elHeaderLink.on('click', this.headerLinkClickHandler.createDelegate(this));
        }
    },
    
    headerLinkClickHandler : function( e, t, o ) {
        e.stopEvent();
        App.go( this.initialConfig.northHeader.token );
    }, 

    createDetails : function(config) {
        if ( !config.detailsColumn ) return;
        this.details = new Ext.BoxComponent({
            split: true,
            cls: 'x-grid-details',
            border:true,
            region: 'south',
            bodyStyle:'padding:10',
            margins:'10 10 10 10',
            autoScroll:true,
            html: config.detailsDefaultText,
            height: 200,
            boxMinHeight: 50
        });
    },
   
    createGrid : function(config) {
        if ( !config.reportQuery ) throw new Error("reportQuery undefined");        
        
        var storeConfig = Ext.applyIf ( config.storeConfig, {
            root: 'items',
            totalProperty: 'totalCount',
            remoteSort: false, 
            baseParams: { },
            proxy: new Veeam.RpcDataProxy({ method: 'getGridData' }),
            listeners: { 
                beforeload: this.beforeloadHandler.createDelegate(this),
                load: this.loadHandler.createDelegate(this) 
            }
        });
        
        this.store = new Ext.data.JsonStore( storeConfig );

        // build tool bar
        var tbitems = [];
        var toolbarId = Ext.id(null, 'grid-toolbar-');
        
        // add filters
        var fi = config.filterBarItems;
        if ( fi.length>0 ) {
            for( var i = 0, len = fi.length; i<len; i++ ) { 
                if ( fi[i].filterLabel ) {
                    tbitems[tbitems.length] = { xtype:'tbtext', text:fi[i].filterLabel };
                    tbitems[tbitems.length] = { xtype:'tbspacer'};
                }
                fi[i].id = toolbarId + ':' + fi[i].filterId;
                fi[i].listeners = {specialkey: this.specialkeyHandler.createDelegate(this)};
                fi[i].width = 150;

                tbitems[tbitems.length] = fi[i]; 
                tbitems[tbitems.length] = { xtype:'tbspacer'};
            }
        };

        tbitems[tbitems.length] = { 
            id: Ext.id(null,'refresh-btn-'),  xtype: 'tbbutton', cls: 'x-btn-text-icon',  
            text: (fi.length==0) ? 'Refresh' : 'Find', 
            iconCls: (fi.length==0) ? 'x-refresh' : 'x-search',  
            handler: this.refreshHandler, scope: this
        };
            
        tbitems[tbitems.length] = { xtype: 'tbseparator' }; 
        
        // add server tasks
        var applyTask = function( task ) {
            var h = task.clientHandler ? this[task.clientHandler] : this.taskHandler;
            var id = task.buttonId ? task.buttonId  : Ext.id(null,'task-btn-');
            return Ext.apply( { handler: h, scope:this }, task, { disabled : task.requiryRow, id: id } );
        };
        
        var ti = config.serverTasks;
        for ( var i = 0, len = ti.length; i<len; i++ )
            tbitems[tbitems.length] = applyTask.apply(this, [ti[i]]);
        
        tbitems[tbitems.length] = '->'; 

        // add client tasks
        var ti = config.clientTasks;
        for ( var i = 0, len = ti.length; i<len; i++ )
            tbitems[tbitems.length] = applyTask.apply(this, [ti[i]]);

        // add export excel btn
        tbitems[tbitems.length] = { 
            id: Ext.id(null,'export-btn-'),  xtype: 'tbbutton', 
            text:'Export Excel', cls: 'x-btn-text-icon',  iconCls: 'x-export',  
            handler: this.exportHandler, scope: this
        };

        // add toolbar
        if ( tbitems.length> 0 )
            this.gridToolBar = new Ext.Toolbar({ 
                id: toolbarId,  
                items: tbitems
            });

        if ( !config.autoRefresh ) {
            
            this.gridPagingBar = new Veeam.PagingToolbar({
                id: Ext.id(null,'pgbar-'),
                pageSize: 25,
                store: this.store,
                displayInfo: true,
                displayMsg: 'Displaying items {0} - {1} of {2}',
                emptyMsg: "" 
            });
        };
        
        var selModel = new Ext.grid.RowSelectionModel({
            singleSelect: true,
            listeners: { 
                rowselect: this.rowSelectHandler.createDelegate(this), 
                rowdeselect: this.rowDeselect.createDelegate(this)
            }
        });


        this.rendererDgt = this.cellRenderer.createDelegate(this);
        Ext.each( config.columns, function(c) { c.renderer = this.rendererDgt; }, this);
        
        this.gridView = new Veeam.GridView({ forceFit:true });
       
        var gridConfig = {
            stateId:config.gridId||Ext.id(null, 'autogrid-'),
            enableColumnMove: true,            
            enableColumnHide: false,            
            enableHdMenu: false,
            region:'center',
            split: true,
            layout:'fit',
            store: this.store,
            loadMask: false,
            columns: config.columns,
            stateEvents:['columnmove', 'columnresize'],
            stateful:true,
            listeners: { cellclick: this.cellClickHandler.createDelegate(this) },
            viewConfig: this.gridView,
            bbar: this.gridPagingBar,
            selModel: selModel,
            border:false
        };
        
        this.grid = new Ext.grid.GridPanel(gridConfig);
    },
    
    buildQuery : function() {
        var query = { reportQuery: this.gridConfig.reportQuery, filters:[], metadata:this.gridConfig.metadata };
        
        if ( this.store && this.store.sortInfo ) 
            Ext.apply( query, { sort: this.store.sortInfo.field, dir : this.store.sortInfo.direction });

	    var fk = this.gridConfig.filterKeys||[];
	    var qf = query.filters;
	    for ( var i = 0, len = fk.length; i<len; i++ ) {
	        var f = this.gridToolBar.items.get( this.gridToolBar.id+':'+fk[i]);
	        if ( f ) 
	            qf[ qf.length ] = { filterId: fk[i], value: f.getValue() }; 
        };
        
        return query;
    },
    
    beforeloadHandler: function(store, options) {
        var query = this.buildQuery();
        var limit = (this.gridPagingBar||{}).pageSize||1000000;
        options.params = Ext.apply( { query: query }, options.params||{}, { start: 0, limit: limit });
        Ext.apply( this.store.baseParams, { query : query });
        this.store.baseParams.clearCache = this.store.baseParams.clearCache||(this.gridPagingBar && (this.gridPagingBar.lastCommand=='refresh'));
    },
    
    loadHandler : function() {
        if ( !this.store ) return;
        Ext.applyIf(this.store, {baseParams:{}});
        this.store.baseParams.clearCache = true;
        if ( this.selectedItem ) {
            var i = this.store.findBy( (function(r) { 
                return this.selectedItem.typeId == r.get("objectId").typeId; }
            ), this );
            if ( i>=0 ) this.grid.getSelectionModel().selectRow(i);
            else { 
                this.selectedItem = null;                
                this.rowDeselect();
            }
        };
    
        if ( this.autoRefresh ) {
            var rowCount = this.grid.getStore().getCount();
            if (this.initialConfig.preventAutoFocus !== true){
                if (rowCount > 0) this.grid.getView().focusRow(rowCount-1);
            }
            this.doLoad.defer( 30000, this );
        }
    },
    
    resizeHandler: function( c, aw, ah, rw, rh) {
        var w = this.gridConfig.detailsColumnWidth;
        if ( w ) { this.details.width = (w>1.0) ? w : (aw*w); }
    },
    
    specialkeyHandler : function(el, e) {
        if ( e.keyCode == 13 )
            this.refreshHandler.defer(500, this);
    },
    
    refreshHandler : function() {
        if ( !this.store ) return;
        App.registerActivity();
        Ext.apply( this.store.baseParams, { clearCache : true });
        this.store.load();
    },
    
    wait : function( msg ) {  Ext.MessageBox.show({ title: 'Please wait',  msg: msg, width:400,  wait:true, waitConfig: { interval:500 },  closable:false  });   },
    progress : function( msg ) { return this.wait(msg); },

    exportHandler : function() {
        var query = this.buildQuery();
        var params = Ext.apply( { query: query }, {}, { start: 0, limit: 10000000 });
        
        var callbackFn = function(r) {
            this.currentTaskKey = r.taskKey; 
            this.progress('Preparing data...');
            var successFn = function( id ) { 
                var url = 'ExportExcel.aspx?id=' + this.currentTaskKey;
                if ( Ext.isIE ) { window.navigate(url); }
                else { window.open(url, '_self'); }
            };
            this.taskProgressHandler( null, successFn );
        };
        
        ext_channel( CommonDataHandler.rpc.prepareExcelData( params, callbackFn.createDelegate(this)) );
    },
    
    taskProgressHandler : function( r, callback ) {
        if ( !r || (typeof(r.success) == 'undefined' && (r.progress||0) < 0.999999 )) {
            Ext.MessageBox.updateProgress( (r||{}).progress||0);
            var cb = this.taskProgressHandler.createDelegate(this, [callback], true );
            var args = CommonDataHandler.rpc.checkProgress( { taskKey:this.currentTaskKey}, cb );
            ext_channel.defer( 3000, this, [args]); 
            return;
        }
        var success = (( typeof(r.success) != 'undefined' ) && r.success ) || true;
        if ( !success || !callback ) {
            Ext.MessageBox.show({ title: 'Status',
                msg: r.message || Ext.encode(r),
                width:400,
                buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox[success ? "INFO" : "ERROR"]
           });
        } else {
            Ext.MessageBox.hide();
            callback.apply(this, []);
        }
    },

    cellRenderer : function( value, meta, record ) {
        if (typeof(value) == 'string' ) return value;

        if ( record.data.color && meta.id.indexOf('severity') != -1){
            switch (record.data.color.value.toLowerCase()) {
                case "#7dff7d":
                    meta.css = 'x-success';
                    break;
                case "#ff7d7d":
                      meta.css = 'x-error';
                      break;
                case "#ffff7d":
                      meta.css = 'x-warning';
                      break;
                default:
                      meta.css = 'x-none';
                      break;
            }
        }
        
        meta.css +=  ' ' + value.css;

        if ( value.isImage ) {
            meta.attr += ' valign="middle" align="center" ';
            return '&nbsp;';
        }  

        if ( value.container && value.value) {
            return '<a href="#" id="' + Ext.id(null,'autolink-') + '">' +  value.value + '</a>';
        } else { 
            meta.attr += 'ext:qtip=\''  + value.value.replace(/'/g,  "\"") + '\'';
            return value.value||'&nbsp;'; 
        } 
        
    }, 
   
    cellClickHandler: function( grid, ri, ci, e ) {
        e.stopEvent();
        if ( e.getTarget().tagName != "A" ) return;
        
        var cm = grid.getColumnModel();
        var r = grid.getStore().getAt(ri);
        var c = cm.getColumnById(ci);
        var fieldName = cm.getDataIndex(ci);
        var data = r.get(fieldName);    
        if ( data.reportQuery && data.reportQuery.isDynamic ) {
            var fn = function(token) {
                App.go( token);
            };
            ext_channel(CommonDataHandler.rpc.getDynamicLink( data.reportQuery,  fn));
        } else if (data.container && data.value ) {
            var cc = { query: data.reportQuery, xtype:'vm.ui.metadataloader' };
            App.go({ 
                container: data.container, 
                displayName : data.reportQuery.displayName,
                contentConfig: cc 
            });
        }
    }, 
    
    rowClickHandler: function( grid, ri, e ) {
    },
    
    rowSelectHandler : function ( sm, ri, r ) {
        var r = this.store.getAt(ri);
        this.selectedItem = r.get('objectId');
        
        var data = r.get(this.gridConfig.detailsColumn);
        if (this.details && this.details.el)
            this.details.el.update('<nobr>' + data + '</nobr>');

        var items = this.gridToolBar.items;     
        for ( var i=0, len = items.items.length; i < len; i++) {
            var c = items.get(i);
            if ( c.xtype=='vm.ui.taskbutton')
                c.enable();
        }
    },
    
    rowDeselect : function()    {
        if (this.details && this.details.el) {
            var text = this.initialConfig.detailsDefaultText || '';
            this.details.el.update(text);
        }
        
        var items = this.gridToolBar.items;     
        for ( var i=0; i<items.items.length; i++) {
            var c = items.get(i);
            if ( c.xtype=='vm.ui.taskbutton' && c.requireRow )
                c.disable();
        }
    },
    
    taskHandler : function( ti )  {
        if ( ( (!this.selectedItem) && ti.requireRow ) || this.startingTask) { return; }
        
        var arg = { taskId : ti.taskId, objectId: this.selectedItem };
        this.wait('Executing...');
        ext_channel( CommonDataHandler.rpc.executeTask( arg, this.taskExecuteCompleted.createDelegate(this) ));
    },
    
    taskCredsHandler: function(w, request) {
        this.wait('Executing...');
        if (w) request.creds = w.captureData();
        ext_channel( CommonDataHandler.rpc.executeTask( request, this.taskExecuteCompleted.createDelegate(this) ));
    },
    
    taskExecuteCompleted : function(result) {
        this.startingTask = false;
        
        if (result.needConfirm === true){
            Ext.MessageBox.hide();
            
            var callback = function(buttonId, text, opt, request){
                if (buttonId == 'ok'){
                    // add ok flag
                    request.confirmed = true;
                    this.taskCredsHandler.apply(this, [null, request]);
                }
            }
            
            var cd = Ext.Msg.show({
               title: 'Veeam Backup Enterprise Manager', 
               msg: result.message,
               buttons: Ext.Msg.OKCANCEL,
               minWidth: 300,
               fn: callback.createDelegate(this, [ result.request ], true),
               icon: Ext.MessageBox.QUESTION
            });
            
            return;
        }
        
        if ( result.request ) {
            Ext.MessageBox.hide();
            var cw = new Veeam.CredentialsWindow({
                listeners: { commit : this.taskCredsHandler.createDelegate(this, [result.request], true) }
            });
            cw.show();
            return;
        };
        
        if ( (result||{}).message ) {
            Ext.MessageBox.show({ title: 'Veeam Backup Enterprise Manager', width:400,
                msg: (result||{}).message,
                buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox[result.success ? "INFO" : "ERROR"]
           });
        };
       
       this.check4update();
    },
    
    check4update : function() {
        if ( !this.activated ) return;
        ext_channel(CommonDataHandler.rpc.check4updates( this.gridConfig.reportQuery, 
            this.check4updateHandler.createDelegate(this) ));
    },
    
    doLoad : function() {
        if ( !this.activated ) return;
        if ( this.store )
            this.store.load();
    },
    
    check4updateHandler : function(result) {
        if (!this.store)
            return;
        this.store.load();
        if ( this.activated ) 
            this.timeoutId = this.check4update.defer(result.period||30000, this);
    },
    
    activateContent : function() {
        this.doLayout();
        this.store.baseParams.clearCache = true;
        this.store.load();
        this.store.baseParams.clearCache = false;
        this.activated = true;

        // improve combobox presentation
        var items = this.gridToolBar.items.items;
        for (var i = 0; i < items.length; i++) {
            if (items[i].xtype == 'vm.ui.combobox' && typeof (items[i].forceWidth) != 'undefined') {
                items[i].forceWidth(150);
            }
         }
         
    }, 
    
    deactivateContent : function() {
        this.activated = false;
        this.store.removeAll();
    },
    
    calcPageSize : function() {
        var oparent = this.ownerCt.bwrap ? this.ownerCt.bwrap.dom : this.ownerCt.el.dom;
        while ( oparent.offsetHeight == 0 ) {
            oparent = oparent.parentNode;
        }

        var bodyh = Ext.getBody().dom.offsetHeight;
        var st = Ext.isIE ? window.screenTop : 100;
        var refh = screen.availHeight - st - (bodyh - oparent.offsetHeight) - 50;
        if ( this.gridPagingBar )
            refh -= 30; 

        var n = refh/18;
        if ( n>45 ) return 50;
        else if ( n>35 ) return 40;
        else if ( n>25 ) return 30;
        else if ( n>15 ) return 20;
        else return 10;
    },
    
    showMsg : function( result ) {
        Ext.MessageBox.show({ title: 'Veeam Backup Enterprise Manager', 
            msg: result.message||'Success.',
            width:400, 
            buttons: Ext.MessageBox.OK, 
            icon: Ext.MessageBox[result.success ? "INFO" : "ERROR"]
        });
    },
    
    showWait : function( msg ) {
        Ext.MessageBox.show({ title: 'Please wait',  msg: msg, width:400,  wait:true, waitConfig: { interval:500 },  closable:false  }); 
    },
    
    startAutoUpdate: function(interval){
       if (typeof this.autoUpdateTask == "undefined"){
            this.autoUpdateTask = {
                run: function(){
                    this.store.reload();
                },
                interval: interval || 3000,
                scope: this
            }
       }
       
       if (!this.updateRunning){
            Ext.TaskMgr.start(this.autoUpdateTask);
            this.updateRunning = true;
       }
    },
    
    stopAutoUpdate: function(){
        if (this.autoUpdateTask) {
            Ext.TaskMgr.stop(this.autoUpdateTask);
        }
    },

    onDestroy: function(){
        if (this.timeoutId){
            window.clearTimeout(this.timeoutId);
            delete this.timeoutId;
        }
        Veeam.AutoGridPanel.superclass.onDestroy.apply(this);
    }
});

Veeam.AutoGridPanel.temp = 100;
Ext.reg( 'vm.ui.autogrid', Veeam.AutoGridPanel );



/* 
    LogPanel
*/
Veeam.LogPanel = function( config ) {
    Veeam.LogPanel.superclass.constructor.apply( this, [config] );
};
 
Ext.extend( Veeam.LogPanel, Ext.Panel, {
    updateContent : function() {
    },
    
    activateContent : function() {
    },
    
    deactivateContent : function() {
    }
});

Ext.reg( 'vm.ui.logpanel', Veeam.LogPanel );