﻿    Veeam.RestorePanel = Ext.extend(Ext.Panel, {
        constructor: function(cfg){
            var c = cfg || {};

            var pageSize = c.pageSize || 15;

            this.initialLoad = true;
            this.store = new Ext.data.JsonStore({
                proxy: new Veeam.RpcDataProxy({ method: 'restore.getSessions' }),
                root: 'items',
                totalProperty: 'totalCount',
                remoteSort: true,
                baseParams: {
                    start: 0,
                    limit: pageSize
                },
                sortInfo: {
                    field: 'dateStart',
                    direction: 'DESC'
                },
                fields: [
                    'uid', 'dateStart', 'status', 'dateEnd', 'total', 'progress', 'type', 'target_path', 'initiator'
                ]
            });

            this.pageBar = new Ext.PagingToolbar({
                pageSize: pageSize,
                store: this.store,
                displayInfo: true,
                displayMsg: 'Displaying sessions {0} - {1} of {2}',
                emptyMsg: 'No sessions found'

            });


            var statusRenderer = function(status, meta){
                var cls, 
                    lc = Ext.util.Format.lowercase(status);
                if (lc == "inprogress"){
                    status = "Restore in progress";
                    cls = 'x-restoring';
                } else { 
                    cls =' x-' + lc;
                }
                
                meta.css += cls;
                
                return status;
            };

            this.grid = new Ext.grid.GridPanel({
                id: 'sessionsGrid',
                store: this.store,
                region: 'center',
                boxMinHeight: 200,
                autoScroll: true,
                stateful: false,
                enableDragDrop: false,
                enableHdMenu: false,
                columns: [
                    {
                        id: 'initiator-col',
                        header: 'Initiated by',
                        dataIndex: 'initiator'
                    },
                    {
                        id: 'startdate-col',
                        header: 'Started at',
                        dataIndex: 'dateStart'
                    },
                    {
                        id: 'status-col',
                        header: 'Status',
                        dataIndex: 'status',
                        renderer: statusRenderer
                    },
                    {
                        id: 'enddate-col',
                        header: 'Ended at',
                        dataIndex: 'dateEnd'
                    },
                    {
                        id: 'total-col',
                        header: 'Total objects',
                        dataIndex: 'total'
                    },
                    {
                        id: 'progress-col',
                        header: 'Progress',
                        dataIndex: 'progress',
                        renderer : function(prg, column, record){ return String.format("{0}%", prg); }
                    },
                    {
                        id: 'type-col',
                        header: 'Target',
                        dataIndex: 'type'
                    }
                ],
                sm: new Ext.grid.RowSelectionModel({ singleSelect: true }),
                viewConfig: { forceFit: true },
                bbar : this.pageBar
            });

            this.grid.getSelectionModel().on('rowselect',
                function(sm, rowIdx, r) {
                    // Get log
                    var sid = r.get('uid');
                    this.sessionStore.setBaseParam('sid', sid);
                    this.sessionStore.reload();
                    this.reloadLog(sid);
                },
                this
            );


            this.sessionStore = new Ext.data.JsonStore({
                proxy: new Veeam.RpcDataProxy({ method: 'restore.getSessionFileLog' }),
                root: 'items',
                totalProperty: 'totalCount',
                remoteSort: true,
                fields: [
                    'sourceItemName', 'sourceItemPath', 'targetItemName', 'targetItemPath', 'itemSize', 'host', 'pointDatetime', 'isRestored'
                ],
                listeners: {
                    'exception' : this.handleException.createDelegate(this)
                }

            });

            this.fileLogListView = new Ext.list.ListView({
                store: this.sessionStore,
                multiSelect: false,
                columnSort: false,
                reserveScrollOffset: true,
                columns: [{
                    header: 'Source item',
                    dataIndex: 'sourceItemName'
                },{
                    header: 'Source path',
                    dataIndex: 'sourceItemPath'
                },{
                    header: 'Target item',
                    dataIndex: 'targetItemName'
                },{
                    header: 'Target path',
                    dataIndex: 'targetItemPath'
                },{
                    header: 'Restore point',
                    dataIndex: 'pointDatetime'
                },{
                    header: 'VM',
                    dataIndex: 'host'
                },{
                    header: 'Size',
                    dataIndex: 'itemSize',
                    tpl: '{itemSize:fileSize}' // format using Ext.util.Format.fileSize()
                },
                {
                    header: 'Is restored',
                    dataIndex: 'isRestored',
                    width: .05,
                    align: 'center',
                    tpl: '<div class="x-log-record x-log-<tpl if="isRestored">success</tpl><tpl if="isRestored==false">error</tpl>"></div>'
                }
                ]
            });


            this.fileLogPn = new Ext.Panel({
                title: 'Details',
                id: 'restore-session-details',
                layout: 'fit',
                boxMinHeight: 100,
                bbar: [ new Ext.Button({ iconCls: 'x-refresh', cls: 'x-btn-gray',  handler: this.reloadDetails, scope: this }) ],
                items: this.fileLogListView,
                scope: this,
                listeners: {
                    'activate' : this.reloadDetails.createDelegate(this)
                }
            });


            this.detailsPnTmpl = new Ext.XTemplate(
                '<div class="x-session-details">',
                '<tpl for=".">',
                '<div class="x-log-record-wrap">',
                '<div class="x-log-severity x-log-{severity}"></div>',
                '<div class="x-log-record" ext:qtip="event time: {eventTime}"><span>{message}</span></div>',
                '</div>',
                '</tpl>',
                '</div>'
            ).compile();

            this.detailsPn = new Ext.Panel({
                title: 'Log',
                id: 'restore-session-log',
                layout: 'fit',
                bodyStyle: {
                    //background: '#fff',
                    padding: '10px'
                },
                autoScroll: true,
                tmpl: this.detailsPnTmpl,
                html: 'Please select record',
                boxMinHeight: 100,
                bbar: [ new Ext.Button({ iconCls: 'x-refresh', cls:'x-btn-gray',  handler: function(){ this.reloadLog( this.sessionStore.baseParams["sid"] ); }, scope: this }) ]
            });

            this.sessionInfoPn = new Ext.TabPanel({
                activeItem: 1,
                border: false,
                deferredRender: false,
                id: 'restore-session-info',
                items: [  this.fileLogPn, this.detailsPn  ]
            });



            var hidden = App.user && App.user.canRestore() == false;
            c = Ext.applyIf({
                id: 'veeam-restore-panel',
                layout: 'border',
                title: 'Restore sessions',
                border: false,
                hidden: hidden,
                autoScroll: true,
                tabCls: 'right-tab x-hidden', // hide tab header
                items: [this.grid,
                    {
                        xtype: 'container', layout: 'fit', region: 'south',
                        height: 200, boxMinHeight: 100,
                        split: true, items: this.sessionInfoPn
                    }
                ],


                listeners: {
                    'activate': this.reloadSessions.createDelegate(this)
                }
            }, c);

            Veeam.RestorePanel.superclass.constructor.call(this, c);
        },

        initComponent: function(){
            Veeam.RestorePanel.superclass.initComponent.call(this);
            this.addEvents('restorestarted');

            // Attach global listener to start/stop autoupdate grid when restore in progress
            Ext.util.Observable.observeClass(Veeam.RestoreSessionUpdater, {
                'init' : this.startAutoUpdate,
                'destroy' : this.stopAutoUpdate,
                scope: this
            });


            this.store.on('beforeload', this.onReload, this);
        },

        handleException: function(store, type, param, o, result)
        {
            return Veeam.Msg.error({msg: result.message });
        },

        onReload: function(store, options){
            var sm = this.grid.getSelectionModel();
            var reselect = null;
            if ( sm && sm.hasSelection()) {
                  var selection = sm.getSelections();
                  for (var i = 0; i < selection.length; i++) {
                     selection[i] = this.store.indexOf(selection[i]);
                  }
                  reselect = function() {
                      for (var i = 0; i < selection.length; i++) {
                          sm.selectRow(selection[i]);
                      }
                  }
            }
            options.callback = reselect;
        },

        reloadSessions: function(){
            if (!this.isVisible())
                return // do no update ui if panel is inactive
            var lastOptions = this.store.lastOptions;
            this.store.reload(lastOptions);
            this.initialLoad = false;
        },

        reloadDetails: function(p){
            this.sessionStore.removeAll();
            if (!this.sessionStore.baseParams.sid)
                return
            this.sessionStore.load()

        },

        reloadLog: function(sid){
            if (!sid)
                return
            var callback = function(response){
                if (response.success === false){
                    return Veeam.Msg.error({
                        msg: response.message
                    });
                }

                var log = response.log;
                this.detailsPnTmpl.overwrite(this.detailsPn.body, log);
            }

            CommonDataHandler.rpc["restore.getSessionLog"](sid, callback.createDelegate(this)).call(ext_channel);
        },

        goToLastSession: function(){
            this.sessionStore.addListener('load', function(){
                this.grid.getSelectionModel().selectFirstRow();
            }, this, { single: true });
        },

        startAutoUpdate: function(interval){
            if (!this.updateTask){
                this.updateTask = {
                    run: function(){
                        this.reloadSessions();
                    },
                    interval: interval || 3000,
                    scope: this
                };

                Ext.TaskMgr.start(this.updateTask);
            }
        },

        stopAutoUpdate: function(){
            if (this.updateTask){
                if (Veeam.RestoreSessionUpdaterManager.haveRunningSessions() == false){
                    Ext.TaskMgr.stop(this.updateTask);
                    this.updateTask.run.call(this); // properly refresh completed session
                    delete this.updateTask;
                }
            }

        },


        selectRecord: function(sessionId){
            if (!sessionId)
                return;

            if (this.initialLoad == true && this.store.getCount() == 0){
                this.store.on('load', this.selectRecord.createDelegate(this, [sessionId]), this, {single: true });
                return;
            };

            var recIdx = this.store.find('uid', sessionId);

            if (recIdx >= 0)
                this.grid.getSelectionModel().selectRow(recIdx);


        }

    });

    Veeam.RestorePanel.prototype.getInstance = function(){
        return Ext.getCmp('veeam-restore-panel');
    };

    Veeam.RestorePanel.prototype.credentialPromtCallback = function(response, files, pn){
        if (response.success == false && response.promt){
                 var promtObj = response.promt,
                     promts = promtObj.promts,
                     promtsCounter = promts.length;


                 var promtWindowOkCallback = function(){
                     var creds = this.captureData();
                     if (creds.username.length == 0) {
                         this.promt.credsExist = false;
                         this.promt.creds = null;

                     } else {
                         creds.password = Base64.encode( creds.password );
                         this.promt.creds = creds;
                         this.promt.credsExist = true;

                     }

                 };

                 var promtWindowCloseCallback  = function(){

                      if (--promtsCounter == 0 && credsNotEmpty()) {

                         CommonDataHandler.rpc["restore.restoreFiles"]( 2, null, files || null, promtObj, Ext.emptyFn ).call(ext_channel);
                         Veeam.RestorePanel.prototype.getInstance().fireEvent('restorestarted', { sessionId: response.promt.sessionId, files: files } );
                         //Ext.Msg.alert("Status", "Restore operation started.");
                      }
                 };

                 var createPromtWindow = function(promt){
                     var win = new Veeam.CredentialsWindow({});
                     win.setTitle(Ext.util.Format.ellipsis(promt.vmName + ": enter guest OS credentials", 33));
                     win.promt = promt;
                     win.on('commit', promtWindowOkCallback, win);
                     win.on('close', promtWindowCloseCallback, win);
                     win.show();
                 }

                 var credsNotEmpty = function () {
                     var ret = false;
                     for (var i = 0, l = promts.length; i < l; i++) {
                         if (promts[i].credsExist) {
                             ret = true;
                             break;
                         }
                     }

                     return ret;
                 }

                 for (var i=0, l = promts.length; i < l; i++){
                     createPromtWindow(promts[i]);
                 }
        } else if (response.success == false){
              if (pn) pn.fireEvent('restorefailed');
              return Veeam.Msg.error({ msg: response.message });
        } else if (response.success == true){
              Veeam.RestorePanel.prototype.getInstance().fireEvent('restorestarted', { sessionId: response.message, files: files } );
              //return Ext.Msg.alert("Status", "Restore operation started.");
        }
    }


    /* Restore List */
    Veeam.RestoreList = Ext.extend(Ext.Panel, {
        constructor: function (cfg) {
            var c = cfg || {};

            this.store = new Ext.data.JsonStore({
                root: 'items',
                totalProperty: 'totalCount',
                remoteSort: true,
                //            sortInfo: {
                //                field: 'm_backedUpPath',
                //                direction: 'ASC'
                //            },
                fields: [
                    'id',
                    'm_item', 'm_isDir',
                    'm_backedUpPath',
                    { name: 'm_modified', type: 'date', dateFormat: 'timestamp' },
                    { name: 'm_vmName' },
                    'm_fileOwnerName', 'm_fileSize',
                    { name: 'm_oibId', mapping: 'm_restorePoint.m_oibId' },
                    { name: 'm_backupDate', mapping: 'm_restorePoint.m_backupDate', type: 'date', dateFormat: 'timestamp' },
                    'm_isOibRegistered'
                ]
            });
            
            var canRestore = App.isEnterpriseLicense() && App.user && App.user.canRestore() === true;
            var canDownload = canRestore;
            if (canRestore) {
                canDownload = App.user.canDownload() === true;
            }

            this.downloadBtn = new Ext.Button({
                xtype: 'button', width: 120, iconCls: 'x-download', cls: 'x-btn-gray',
                text: 'Download',
                handler: this.startRestoreHandler.createDelegate(this, [1], true),
                scope: this,
                disabled: !canDownload
            });

            this.restoreBtn = new Ext.Button({
                xtype: 'button', width: 120, iconCls: 'x-restore', cls: 'x-btn-gray',
                text: 'Restore',
                handler: this.startRestoreHandler.createDelegate(this, [2], true),
                scope: this,
                disabled: !canRestore
            });


            var actions = {
                'select_all': function () {
                    this.grid.getSelectionModel().selectAll();
                },
                'clear_selected': this.emptyList,
                'clear_all': function () {
                    this.grid.getSelectionModel().clearSelections();
                }
            };

            var selectAllLink = new Veeam.Link({
                text: 'Select all',
                handler: actions['select_all'],
                scope: this
            });

            var clearAllLink = new Veeam.Link({
                text: 'Clear all',
                handler: actions['clear_all'],
                scope: this
            });


            var removeSelectedLink = new Veeam.Link({
                text: 'Remove selected',
                handler: actions['clear_selected'],
                scope: this,
                width: 120
            });



            this.topCnt = new Ext.Container({
                region: 'north',
                height: 50,
                style: { backgroundColor: '#fbfbfb' },
                layout: { type: 'hbox', flex: 1, pack: 'start', align: 'middle', defaultMargins: '0 5 0 5' },
                items: [
                //{ xtype: 'button', width: 120, text: 'Clear selected', cls: 'x-btn-gray', iconCls: 'x-recycle', handler: this.emptyList, scope: this },
                    this.restoreBtn,
                    this.downloadBtn,
                    { xtype: 'box', flex: 3 },
                    selectAllLink,
                    { xtype: 'box', html: ' | ' },
                    clearAllLink,
                    { xtype: 'box', html: ' | ' },
                    removeSelectedLink
                ]
            });

            var itemTypeRenderer = function (item, column, record) {
                var isFolder = record.get('m_isDir');
                return String.format('<div class="x-ico {0}"><div class="x-status-icon">{1}</div></div>', isFolder ? 'x-folder' : 'x-file', item);
            };

            var sm = new Ext.grid.CheckboxSelectionModel({ checkOnly: true, header: '' });



            this.grid = new Ext.grid.GridPanel({
                id: 'restoreListGrid',
                store: this.store,
                region: 'center',
                enableDragDrop: false,
                stateful: false,
                enableHdMenu: false,
                columns: [
                    sm,
//                    {
//                        id: 'item-type-id',
//                        header: ' ',
//                        width: 20,
//                        dataIndex: 'm_item',
//                        renderer: itemTypeRenderer
//                    },
                    {
                        id: 'item-col',
                        header: 'Item',
                        dataIndex: 'm_item',
                        renderer: itemTypeRenderer
                    },
                    {
                        id: 'path-col',
                        header: 'Source path',
                        dataIndex: 'm_backedUpPath'
                    },
                    {
                        id: 'retorepoint-col',
                        header: 'Restore point',
                        dataIndex: 'm_backupDate',
                        renderer: Ext.util.Format.dateRenderer(Veeam.Defaults.dtFormat)
                    },
                    {
                        id: 'vm-col',
                        header: 'VM',
                        dataIndex: 'm_vmName',
                        renderer: function (value) { return value["vmDisplayName"] }
                    },
                    {
                        id: 'size-col',
                        header: 'Size',
                        dataIndex: 'm_fileSize',
                        renderer: function (size) { return Ext.util.Format.fileSize(size) }
                    },
                    {
                        id: 'mod-col',
                        header: 'Modification time',
                        dataIndex: 'm_modified',
                        renderer: Ext.util.Format.dateRenderer(Veeam.Defaults.dtFormat)

                    },
                    Veeam.RestoreHelper.statusColumn()
                ],
                sm: sm,
                viewConfig: { forceFit: true }
            });

            this.grid.getSelectionModel().on('rowselect', Ext.emptyFn);

            var toolbar = new Ext.Toolbar({
                items: [
                    { xtype: 'tbspacer', width: 20, height: 25 },
                    { xtype: 'tbfill' },
                    {
                        xtype: 'vm.ui.link',
                        text: 'View history',
                        scope: this,
                        handler: function () { this.fireEvent('showhistory') }
                    }
                ]
            });


            this.unprocessedRecordsSearcher = function(r, id){
                return typeof(r.get('session_id')) === 'undefined';
            }


            var hidden = App.user && App.user.canRestore() == false;
            c = Ext.applyIf({
                id: 'veeam-restore-list',
                bodyCssClass: "x-veeam-restore-list-body",
                layout: 'border',
                title: 'Pending restore (0)',
                hidden: hidden,
                border: true,
                iconCls: 'x-restore-list',
                tabCls: 'restore-list-tab x-hidden',
                items: [this.topCnt, this.grid],
                bbar: toolbar
            }, c);

            Veeam.RestoreList.superclass.constructor.call(this, c);
        },

        initComponent: function () {
            Veeam.RestoreList.superclass.initComponent.call(this);
            this.addEvents('removeitem', 'showhistory', 'beforerestore', 'restorefailed');
            this.store.on('add', this.listChangeHandler, this);
            this.store.on('remove', this.listChangeHandler, this);
            this.store.on('remove', function (store, record, index) {
                var id = record.id;
                this.fireEvent('removeitem', this, id, true);
            }, this);



            var clickProxy = function (grid, rowIndex, columnIndex, e) {
                var target = e.getTarget(null, null, true);

                if (target && Ext.DomQuery.is(target.dom, 'a.x-view-history')) {
                    e.stopEvent();
                    var session_id = target.getAttributeNS('ext', 'session_id');
                    this.fireEvent("showhistory", session_id);
                    return;
                }
            };

            this.grid.on('cellclick', clickProxy, this);

        },

        addRestoreItem: function (o) {
            var key = this._getKey(o);
            if (this.store.indexOfId(key) != -1)
            // record exists. return
                return -1;

            var recordData = this.prepareObjectData(o);

            var r = new this.store.recordType(recordData, key);
            r.json = o;
            this.store.insert(0, r);
            var selectorFn = function(){
                var records = this.store.queryBy(this.unprocessedRecordsSearcher);
                this.grid.getSelectionModel().selectRecords(records.getRange());
            };

            if (this.grid.rendered == false) {
                this.grid.on('viewready', function (grid) {
                    selectorFn.call(this);
                }, this, { single: true });
            } else {
                selectorFn.call(this);
            }
        },

        removeRestoreItem: function (o) {
            var key = this._getKey(o);
            var i = this.store.indexOfId(key);
            if (i != -1)
                this.store.removeAt(i);

        },

        itemExists: function (o) {
            var key = this._getKey(o);
            return this.itemKeyExists(key);
        },

        itemKeyExists: function (key) {
            return this.store.indexOfId(key) != -1;
        },

        _getKey: function (o) {
            return String.format("{0}_{1}", typeof (o.m_restorePoint) != 'undefined' ? o.m_restorePoint.m_oibId : o.m_oibId, o.m_backedUpPath);
        },

        listChangeHandler: function (store) {
            var count = store.getCount();
            this.setTitle('Pending restore (' + count + ')');
            var tab = Ext.fly(this.tabEl);
            tab[count < 1 ? 'addClass' : 'removeClass']('x-hidden');
        },

        prepareObjectData: function (o) {
            // Convert search result object
            var itemName = o.m_backedUpPath.replace(/^.*\\/, '');

            var recordData = Ext.applyIf({
                m_item: itemName,
                m_isDir: o.m_isDir || false
            }, o);

            if (o.m_restorePoint) {
                recordData = Ext.applyIf(recordData, {
                    m_oibId: o.m_restorePoint.m_oibId,
                    m_backupDate: new Date(o.m_restorePoint.m_backupDate * 1000)
                });
            }

            if (Ext.isDate(recordData.m_modified) == false)
                recordData.m_modified = new Date(o.m_modified * 1000);

            return recordData;
        },

        createObjectJson: function (o) {

            var recordData = Ext.apply({}, o);

            recordData = Ext.applyIf(recordData, {
                m_restorePoint: {
                    m_oibId: o.m_oibId,
                    m_backupDate: o.m_backupDate.format('U')
                }
            });

            recordData.m_modified = o.m_modified.format('U');
            recordData.m_itemName = o.m_backedUpPath.replace(/^.*\\/, '');
            recordData.isDir = false;

            return recordData;
        },

        startRestoreHandler: function (btn, e, restoreType) {

            // check if list not empty
            var records = this.grid.getSelectionModel().getSelections() || [];

            if (records.length == 0)
                return Veeam.Msg.error({ msg: 'Select an item to restore.' });

            this.fireEvent('beforerestore');

            var files = [];
            for (var i = 0, l = records.length; i < l; i++) {
                files.push(records[i].json);
            }

            var restoreBtn = btn;
            var cbFn = function (response, files) {
                restoreBtn.enable();
                this.body.unmask();
                // TODO: get restore session id
                if (response.success === false && !response.promt) {
                    this.fireEvent('restorefailed');
                    return Veeam.Msg.error({ msg: response.message });
                }

                Veeam.RestorePanel.prototype.credentialPromtCallback.call(this, response, files, this);
            };

            this.body.mask();

            CommonDataHandler.rpc["restore.restoreFiles"](restoreType, null, files || null, null, cbFn.createDelegate(this, [files || null], true)).call(ext_channel);
            // prevent multi-click
            restoreBtn.disable();
            // Clear restore list
            // this.store.removeAll();
            this.listChangeHandler.call(this, this.store);
        },

        clearList: function () {
            this.store.removeAll();
        },

        goToSessionLog: function (sid) {
            Ext.getCmp('search-type-tab').setActiveTab('veeam-restore-panel');
            var rp = Ext.getCmp('veeam-restore-panel');
            if (rp) {
                rp.startAutoUpdate();
            }
        },

        changeLabel: function (win, options) {
            if (!options)
                return
            var label = Ext.get('restore-loc-text');
            var message = options["destination-type"] == 2 ?
                "Original VM" :
                options["share_path"];
            if (label)
                label.update(message);
            return message;
        },

        emptyList: function (btn) {
            var selected = this.grid.getSelectionModel().getSelections();
            this.store.remove(selected);
            this.listChangeHandler.call(this, this.store);
        },

        checkDownloadReady: function (sid) {

            var session_id = sid;
            var tasks = {};

            var progressWnd = new Veeam.ProgressWindow({
                title: 'Please wait',
                msg: 'Restore in progress',
                width: 300,
                closable: true
            });

            progressWnd.show();
            var pn = Ext.getCmp('veeam-restore-panel');

            var callback = function (response, sid, pn) {
                if (response.success == false) {
                    var t = tasks[sid];
                    Ext.TaskMgr.stop(t);
                    if (typeof t != 'undefined')
                        Ext.TaskMgr.stop(t);
                    if (pn && pn.stopAutoUpdate)
                        pn.stopAutoUpdate.call(pn);
                    progressWnd.updateText(String.format('Error occured. {0}', response.message));

                }

                var progress = response.progress;
                progressWnd.updateProgress(parseInt(progress) / 100);
                if (response.complete === true) {
                    if (response.link) {
                        var msg = String.format('File restore completed successfully. <a href="{0}" target="_blank">Click this link</a> to download the package with restored files.', response.link);
                        progressWnd.updateText(msg);
                        progressWnd.updateProgress(100);
                    } else {
                        progressWnd.updateText('Error occured during file restore. See log for details.');
                        progressWnd.updateProgress(100);
                    }
                    var t = tasks[sid];
                    // Stop task
                    if (typeof t != 'undefined')
                        Ext.TaskMgr.stop(t);


                    if (pn && pn.stopAutoUpdate)
                        pn.stopAutoUpdate.call(pn);

                }
            }

            var checkReady = function () {
                CommonDataHandler.rpc["restore.getDownloadLink"](session_id, callback.createDelegate(this, [session_id, pn], true)).call(ext_channel);
            }

            var task = {
                run: checkReady,
                interval: 3000,
                scope: this
                //duration: 10 * 60 * 1000 // 10 min
            }

            tasks[sid] = task;
            Ext.TaskMgr.start(task);
            progressWnd.currentTask = task;
        },

        disableButtons: function (noPermission) {
            this.restoreBtn.disable();
            this.restoreBtn.setTooltip(noPermission === true ? this.RESTORE_BTN_NO_PERMISSION : this.RESTORE_BTN_TOOLTIP);

            this.downloadBtn.disable();
            this.downloadBtn.setTooltip(noPermission === true ? this.RESTORE_BTN_NO_PERMISSION : this.RESTORE_BTN_TOOLTIP);

        },

        disableDownloads: function () {
            this.downloadBtn.hide();

        },

        setFilesRestoreState: function (updtr, files) {
            var store = this.store;
            for (var key in files) {
                var r = store.getById(key);
                if (r) {
                    r.set('status', files[key]);
                    r.set('session_id', updtr.getSessionId());
                   
                }
            }
        }

    });

    Veeam.RestoreList.prototype.RESTORE_BTN_TOOLTIP = 'This functionality requires Veeam Backup & Replication Enterprise edition';
    Veeam.RestoreList.prototype.RESTORE_BTN_NO_PERMISSION = 'Insufficient permissions';


    Veeam.ProgressWindow = Ext.extend(Ext.Window, {
        constructor: function(cfg){
            var cfg = cfg || {};

            this.messageEl = new Ext.Container({ html: cfg.msg, border: false, margins: 5, style: 'text-align: center' });
            this.progressBar = new Ext.ProgressBar({ border: false });
            this.okButton = new Ext.Button({ text: 'OK', handler: this.close, scope: this });
            cfg = Ext.applyIf({
                autoCreate : true,
                resizable:false,
                constrain:true,
                constrainHeader:true,
                minimizable : false,
                maximizable : false,
                stateful: false,
                modal: false,
                shim:true,
                hideBorders: true,
                buttonAlign:"center",
                width:400,
                height:120,
                border: false,
                minHeight: 80,
                plain:true,
                footer:true,
                closable:true,
                items: [ this.messageEl, this.progressBar ],
                fbar: new Ext.Toolbar({
                    items: this.okButton,
                    enableOverflow: false
                })
            }, cfg);

            Veeam.ProgressWindow.superclass.constructor.call(this, cfg);
        },

        updateProgress: function(progress){
            this.progressBar.updateProgress(progress);
        },

        updateText: function(text){
            this.messageEl.update(text);
        },

        destroy : function(){
            if (this.task && this.task.run )
                Ext.TaskMgr.stop(this.task);

            Veeam.ProgressWindow.superclass.destroy.call(this);
        }

    });


    Veeam.RestoreSessionUpdater = Ext.extend(Ext.util.Observable, {
       constructor: function(config){
           this.initialConfig = config;
           this.addEvents('init', 'updatestart', 'updateend', 'updateerror', 'destroy');
           Veeam.RestoreSessionUpdater.superclass.constructor.call(this, config);
           this.init();
       },

       getSessionId: function(){ return this._sessionId },
       init: function(){
           this._sessionId = this.initialConfig.sessionId;
           this._files = new Ext.util.MixedCollection();
           this._addFiles();

           this._task = {
                run: this.getUpdates,
                interval: this.initialConfig.updateInterval || 4000,
                scope: this
           };

           this.runner = new Ext.util.TaskRunner();
           this.runner.start(this._task);
           this.fireEvent('init');
       },

       _addFiles: function(files){
            var files = this.initialConfig.files || [];
            for(var i = 0, l = files.length; i < l; i++){
                var key = this._generateKey(files[i].m_restorePoint.m_oibId, files[i].m_backedUpPath)
                this._files.add(key, Veeam.RestoreSessionUpdater.STATE.RESTORING);
            }
       },

       getUpdates: function(){
            this.fireEvent('updatestart');
            CommonDataHandler.rpc['restore.getSessionStats']({ sid: this._sessionId }, this.updateCallback.createDelegate(this)).call(ext_channel);
       },

       updateCallback: function(response){
            if (response.success == false){
                this.fireEvent('updateerror', response.message);
                this.purgeListeners();
                this.destroy();
            } else {
                var items = response.items;
                for (var i = 0, l = items.length; i < l;  i++ ){
                    var item = items[i];
                    var key = this._generateKey(item.oibId, item.sourceItemPath);
                    var state = this._files.get( key );
                    if (typeof state == 'undefined'){
                        continue;
                    }
                    this._files.replace(key,  item.isRestored ?

                            response.link ?
                                { state:  Veeam.RestoreSessionUpdater.STATE.SUCCESS, link: response.link } :
                                    response.complete == true ?
                                    Veeam.RestoreSessionUpdater.STATE.SUCCESS :
                                    Veeam.RestoreSessionUpdater.STATE.PROCESSING

                            :
                            Veeam.RestoreSessionUpdater.STATE.ERROR);
                }

                if (response.complete == true && items.length == 0){
                    // Error. Mark all files as failed
                    this._files.eachKey( function(key, item){
                        this._files.replace(key, Veeam.RestoreSessionUpdater.STATE.ERROR);
                    }, this);
                }

                this.fireEvent('updateend', this, this._files.map );

                if (response.complete && response.complete == true){
                    // session complete - destroy updater
                    this.destroy();
                }
            }
       },

        destroy: function(){
             Veeam.RestoreSessionUpdaterManager.removeUpdater(this._sessionId);
             if (this._task){
                 this.runner.stop(this._task);
                 delete this._task;
             }
             delete this._files;
             delete this._sessionId;
             this.fireEvent('destroy');
        },

        _generateKey: function(oibId, path){
            return String.format("{0}_{1}", oibId, path);
        }

    });


    Veeam.RestoreSessionUpdater.STATE = {
        'Restoring'     : 0,
        'Success'       : 1,
        'Error'         : 2,
        'Warning'       : 3,
        'Processing'    : 4

    };


    Veeam.RestoreHelper = (function(){
        var renderStatus = function(value, meta, rec, ri, ci, s){
            var html = '';
            if (value === 0){
                html = 'Restoring';
                meta.css += ' x-restoring';
            } else if (value == 1){
                html = 'Success';
                meta.css += ' x-success';
            } else if (value == 2){
                html = String.format('<a href="#" class="x-view-history" ext:session_id="{0}">Error</a>', rec.get('session_id'));
                meta.css += ' x-error';
            } else if (value == 3){
                html = String.format('<a href="#" class="x-view-history" ext:session_id="{0}">Warning</a>', rec.get('session_id'));
                meta.css += ' x-warning';
            } else  if (value == 4){
                html = 'Preparing package';
                meta.css = ' x-restoring';
            } else if (typeof value == "object"){
                html = String.format('<a href="{0}">Download</a>', value.link);
                meta.css += ' x-success';
            }

            return html;
        }


        return {

            statusColumn : function(config){
                return new Ext.grid.Column(Ext.applyIf({
                    header: 'Restore status',
                    id: 'status',
                    sortable: false,
                    hideable: false,
                    dataIndex: 'status',
                    renderer: renderStatus,
                    css: 'vertical-align: middle;'
                }, config));

            }

        }
    })();


    Veeam.RestoreSessionUpdaterManager = (function(){
        var _sessions = new Ext.util.MixedCollection();
        return {
            createUpdater: function(sessionId, files){
                var updater;
                if (_sessions.containsKey(sessionId)){
                    updater = _sessions.get(sessionId);
                    if (updater)
                        return updater;
                }
                updater = new Veeam.RestoreSessionUpdater({sessionId: sessionId, files: files });
                _sessions.add(sessionId, updater);
                return updater;
            },
            removeUpdater: function(sessionId){
                _sessions.removeKey(sessionId);
            },

            haveRunningSessions: function(){
                return _sessions.getCount() > 0;
            }
        }
    })();


    Veeam.RestoreNotifier = Ext.extend(Ext.util.Observable,{
        constructor: function(config){
            Ext.apply(this, config);

            this.target = config.targetPn;
            this.addEvents('init', 'beforestart', 'start', 'end', 'error');
            Veeam.RestoreNotifier.superclass.constructor.call(this);

        },
        prepare: function(pn){
            this.target.startAutoUpdate();
            //this.fireEvent('beforestart');
        },
        fail: function(pn){
            this.target.stopAutoUpdate.defer(2000, this.target);
            //this.fireEvent('error');
        }
    });