﻿Ext.namespace("Veeam.Vm");

/////////////////////////////////////////////////////////////////////////
Veeam.Vm.WizardFactory = {
    create: function (oibId, platform) {
        switch (platform.toLowerCase()) {
            case 'hyper-v':
                return new Veeam.Vm.HyperVRestoreWizard({ oibId: oibId });
                break;
            case 'vmware':
                return new Veeam.Vm.VmwareRestoreWizard({ oibId: oibId });
                break;
            default:
                throw new Error("Unknown platform: " + platform);
        }
    }
}

//////////////////////////////////////////////////////////////////////////
Veeam.Vm.AbstractRestoreWizard = Ext.extend(Ext.ux.Wiz, {
    title: 'Restore Vm',
    cls: 'x-veeam-wizard',
    finishButtonText: 'Restore',
    initComponent: function () {

        var cfg = this.initialConfig;

        this.cards = this.buildCards(cfg);
        this.addEvents('afterfinish');
        this.addListener('beforeshow', this.initData, this, { single: true });
        this.addListener('finish', this.finishHandler, this);

        Veeam.Vm.AbstractRestoreWizard.superclass.initComponent.call(this);

        this.previousButton.hide();
        
    },

    buildCards: function (cfg) {

        this.pointsCtrl = new Veeam.Vm.RestorePointSelectorCtrl({ oibId: cfg.oibId });

        var step1 = new Veeam.Vm.WizardCard({
            title: 'Restore point',
            description: 'Select VM restore point.',
            items: {
                xtype: 'container',
                layout: 'fit',
                id: 'vm-wizard-step-one',
                cls: 'x-veeam-wizard-step-container',
                items: this.pointsCtrl
            }
        });

        return [
            step1
        ];
    },

    loadMaskConfig: {
        'default': 'Loading...'
    },

    initEvents: function () {
        Veeam.Vm.AbstractRestoreWizard.superclass.initEvents.apply(this, arguments);
    },

    initData: function () {
        var callback = function (resonseBody) {

            this.switchDialogState(true);

            if (resonseBody.success === false) {
                this.destroy();
                return Veeam.Msg.error({ msg: resonseBody.message });
            }

            this.pointsCtrl.initData(resonseBody);
        } .createDelegate(this);

        this.switchDialogState(false);
        CommonDataHandler.rpc["vm.getVmRestorePoints"](this.initialConfig.oibId, callback).call(ext_channel);
    },

    finishHandler: function () {
        var r = this.pointsCtrl.listView.getSelectedRecords()[0],
            type = r.get('jobType');
        if (this.checkIfSanSnapshot(type))
             return Veeam.Msg.error({ msg: Veeam.Vm.AbstractRestoreWizard.SAN_RESTORE_ATTEMPT });
        if (this.checkIfTapeJob(type))
             return Veeam.Msg.error({ msg: Veeam.Vm.AbstractRestoreWizard.TAPE_RESTORE_ATTEMPT });


        var data = this.pointsCtrl.getData(),
            callback = function (response) {
                Ext.MessageBox.hide();
                if (response.success === false) {
                    this.close();
                    return Veeam.Msg.error({ msg: response.message });
                }
                this.fireEvent('afterfinish', response.message);
                this.close();
            };

            

        CommonDataHandler.rpc["vm.startVmRestore"](data, callback.createDelegate(this)).call(ext_channel);
        this.hide();
        Ext.MessageBox.wait("Starting restore job", 'Please wait...');
        return false;
    },
  
    destroy: function () {
        //log('Destorying wizard');
        if (this.cards) {
            var i = this.cards.length;
            while (i--) {
                this.cards[i] && this.cards[i].destroy && this.cards[i].destroy();
            }
        }

        this.removeListener('beforeshow', this.initData, this);
        this.removeListener('finish', this.finishHandler, this);

        Veeam.Vm.AbstractRestoreWizard.superclass.destroy.call(this);
    },
    
    checkIfSanSnapshot: function(type){
        return type && type.toLowerCase().indexOf('sanrescan') != -1;
    },
    checkIfTapeJob: function(type){
        return type && type.toLowerCase().indexOf('vmtapebackup') != -1;
    }

});

Veeam.Vm.AbstractRestoreWizard.SAN_RESTORE_ATTEMPT = "Restoring VM from storage snapshot is not possible through this portal.<br/>Contact your backup administrator to perform the restore.";
Veeam.Vm.AbstractRestoreWizard.TAPE_RESTORE_ATTEMPT = "Restoring VM from tape is not possible through this portal.<br/>Contact your backup administrator to perform the restore.";

//////////////////////////////////////////////////////////////////////////
Veeam.Vm.VmwareRestoreWizard = Ext.extend(Veeam.Vm.AbstractRestoreWizard, {
    initComponent: function () {
        Ext.apply(this, {
            platform: 'vmware'
        });
        Veeam.Vm.VmwareRestoreWizard.superclass.initComponent.call(this);
    },

    finishHandler: function(){
         Veeam.Vm.VmwareRestoreWizard.superclass.finishHandler.call(this);    
    }
});



Veeam.Vm.HyperVRestoreWizard = Ext.extend(Veeam.Vm.AbstractRestoreWizard, {
    initComponent: function () {
        Ext.applyIf(this, {
            platform: 'hyper-v'
        });
        Veeam.Vm.HyperVRestoreWizard.superclass.initComponent.call(this);
    }
});

//////////////////////////////////////////////////////////////////////////

Veeam.Vm.WizardCard = Ext.extend(Ext.ux.Wiz.Card, {
    initComponent: function () {
        Ext.apply(this, {
            cls: 'x-veeam-wizard-step'
        });

        Veeam.Vm.WizardCard.superclass.initComponent.call(this);
        this.addEvents('preload', 'preloaded');
    }
});



Veeam.Vm.RestorePointSelectorCtrl = Ext.extend(Ext.Container, {
    initComponent: function () {
        var store,
            listView,
            cbPowerOn;

        store = new Ext.data.JsonStore({
            root: 'items',
            totalProperty: 'totalCount',
            remoteSort: false,
            autoLoad: false,
            fields: [{ name: 'oibId' }, { name: 'backupDate' }, { name: 'pointType' }, { name: 'jobName' }, { name: 'jobType'}],
            proxy: new Veeam.RpcDataProxy({ method: 'vm.getVmRestorePoints' }),
            sortInfo: {
                field: 'backupDate',
                direction: 'DESC'
            }
        });

        listView = new Ext.list.ListView({
            store: store,
            multiSelect: false,
            singleSelect: true,
            emptyText: 'Found 0 restore points',
            layout: 'fit',
            reserveScrollOffset: true,
            columnResize: true,
            columnSort: true,
            height: 200,
            columns: [
                {
                    header: 'Backup date',
                    dataIndex: 'backupDate',
                    width: .3
                },
                {
                    header: 'Type',
                    dataIndex: 'pointType'
                },
                {
                    header: 'Job name',
                    dataIndex: 'jobName'
                }
            ]
        });




        cbPowerOn = new Ext.form.Checkbox({
            id: 'cb__poweron',
            boxLabel: 'Power on VM after restoring',
            value: false
        });




        listView.on('beforeclick', function (view, index, node, e) {
            var r = view.getRecord(node);

            if (r.get('jobType') == 'Replica') {
                this.cbPowerOn.disable();
                this.cbPowerOn.setValue(1);
            } else {
                this.cbPowerOn.enable();

            }

        }, this);

        Ext.apply(this, {
            cls: 'vm__restore-points-ctrl',
            store: store,
            listView: listView,
            cbPowerOn: cbPowerOn,
            items: [
                listView, cbPowerOn
           ]
        });

        Veeam.Vm.RestorePointSelectorCtrl.superclass.initComponent.call(this);
    },

    getData: function () {

        var r = this.listView.getSelectedRecords()[0];
        return {
            oibId: r.get('oibId'),
            powerOn: this.cbPowerOn.getValue()
        };
    },


    initData: function (data) {
        this.store.loadData(data);
        this.listView.select(0, false, true);
    },

    destroy: function () {
        if (this.destroyed === false) {

            this.destroyed = true;

            this.store
                && this.store.destroy
                && this.store.destroy()
                && delete this.store;

            this.listView
                && this.listView.purgeListeners() && this.listView.destoy()
                && delete this.listView;

            this.cbPowerOn
                && this.cbPowerOn.destroy()
                && delete this.cbPowerOn;
        }

        Veeam.Vm.RestorePointSelectorCtrl.superclass.destroy.call(this);
    },

   

});

Ext.reg('veeam.vm.wizardcard', Veeam.Vm.WizardCard);

//////////////////////////////////////////////////////////////////////////

Veeam.Vm.RestoreSessionsView = Ext.extend(Ext.Container, {
    initComponent: function () {

        this.sessionList = new Veeam.Vm.RestoreSessionGrid({ region: 'center', boxMinHeigth: 300 });
        this.logPn = new Veeam.Vm.RestoreSessionLogPanel({ region: 'south', split: true, boxMinHeight: 100, height: 200 });

        var brcrClickHandler = function () {
            var rootPanel = Ext.getCmp('app-root-panel');
            if (!rootPanel)
                throw new Error("Container 'app-root-panel' not found!");
            rootPanel.northPn.reloadPage(Veeam.Vm.RestoreSessionsView.VM_TAB_ID);
        };


        var breadcrumbs = this.breadcrumbs = new Ext.BoxComponent({
            region: 'north',
            border: false,
            cls: 'breadcrumbs-panel-body',
            autoHeight: true,
            margins: '0 0 10 0',
            html: '<a class="x-breadcrumb" href="#">VMs</a> &gt; <span class="x-breadcrumb">Restore sessions</span>',
            id: 'container-breadcrumbs-vms',
            listeners: {
                'afterrender': function () {
                    this.el.on('click', brcrClickHandler,
                            this, { stopEvent: true, delegate: 'a.x-breadcrumb' });
                }
            },
            scope: breadcrumbs
        });


        Ext.apply(this, {
            cls: 'x-restore-sessions-view breadcrumbs-panel',
            layout: 'border',
            items: [this.breadcrumbs, this.sessionList, this.logPn]
        });

        this.logPn.addListener('reloadlog', this.loadLogForSession, this);


        this.sessionList.getSelectionModel().on({
            'rowselect': function (sm, rowIdx, r) {
                // Get log
                var sid = r.get('uid');
                this.loadLogForSession(sid)
            },
            'rowdeselect': function (sm, rowIdx, r) {
                this.loadLogForSession(null);
            },
            scope: this
        });

        this.addListener('afterrender', this.initData, this, { single: true })

        Veeam.Vm.RestoreSessionsView.superclass.initComponent.call(this);
    },

    loadLogForSession: function (sid) {

        var sid = sid || this.sessionList.getSelectedSessionId();
        if (!sid) {
            this.logPn.reloadLog(null); // Clear
        } else {
            var callback = function (response) {
                if (response.success === false) {
                    return Veeam.Msg.error({
                        msg: response.message
                    });
                }
                this.logPn.reloadLog(response);
            }

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

    initData: function () {
        this.sessionList.initData();
        if (this.initialConfig.sid)
            this.sessionList.startAutoUpdate();
    }
});

Veeam.Vm.RestoreSessionsView.VM_TAB_ID = '2b556014-a0bb-4320-adb8-1472c7baeb59'



Veeam.Vm.RestoreSessionGrid = Ext.extend(Ext.grid.GridPanel, {
    initComponent: function () {

        this.store = new Ext.data.JsonStore({
            root: 'items',
            totalProperty: 'totalCount',
            remoteSort: true,
            autoLoad: false,
            sortInfo: {
                direction: 'DESC',
                field: 'dateStart'
            },
            baseParams: {
                start: 0,
                limit: this.initialConfig.pageSize || 15
            },
            fields: [
                'uid', 'vmName', 'dateStart', 'dateEnd', 'initiator', 'status', 'progress'
            ],
            proxy: new Veeam.RpcDataProxy({ method: 'vm.getVmRestoreSessions' })
        });

        this.store.on('beforeload', this.storeReloadHandler, this);

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


        this.colModel = new Ext.grid.ColumnModel({
            defaults: { sortable: true },
            columns: [
                {
                    id: 'vmname-col',
                    header: 'VM name',
                    dataIndex: 'vmName'
                },
                {
                    id: 'initiator-col',
                    header: 'Initiated by',
                    dataIndex: 'initiator'
                },
                {
                    id: 'startdate-col',
                    header: 'Started at',
                    dataIndex: 'dateStart'
                },
                {
                    id: 'enddate-col',
                    header: 'Ended at',
                    dataIndex: 'dateEnd'
                },
                {
                    id: 'status-col',
                    header: 'Status',
                    dataIndex: 'status',
                    renderer: statusRenderer
                }
            //              ,{
            //                  id: 'progress-col',
            //                  header: 'Progress',
            //                  dataIndex: 'progress',
            //                  renderer: function (prg, column, record) { return String.format("{0}%", prg); }
            //               }
            ]
        });

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

        Ext.apply(this, {
            cls: 'x-vm-restore-session-grid',
            stripeRows: true,
            autoScroll: true,
            stateful: false,
            enableDragDrop: false,
            enableHdMenu: false,
            viewConfig: { forceFit: true },
            bbar: this.pageBar
        });



        Veeam.Vm.RestoreSessionGrid.superclass.initComponent.call(this);
    },

    initData: function (data) {
        var st = this.store;
        if (data) {
            st.loadData(data);
            this.getSelectionModel().selectFirstRow();
        } else {
            var initialOptions = Ext.apply({
                dir: st.sortInfo ? st.sortInfo.direction : 'DESC',
                sort: st.sortInfo ? st.sortInfo.field : 'startDate'
            }, st.baseParams);

            st.load({
                params: initialOptions,
                callback: function () {
                    this.getSelectionModel().selectFirstRow();
                },
                scope: this
            });
        }

    },

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

    getSelectedSessionId: function () {
        var r = this.getSelectionModel().getSelected();
        return (typeof r != "undefined") ? r.get('uid') : null;


    },

    startAutoUpdate: function (interval) {
        if (!this.updateTask) {
            this.updateTask = {
                run: function () {
                    this.store.reload();
                },
                interval: interval || 5000, //5 sec
                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;
            // }
        }
    }
});


Veeam.Vm.RestoreSessionLogPanel = Ext.extend(Ext.Panel, {
    constructor: function (cfg) {
        var cfg = cfg || {};

        cfg = Ext.apply(cfg, {
            cls: 'x-restore-session-log',
            id: 'restore-session-log',
            autoScroll: true,
            emptyText: 'Please select record'
        });
        Veeam.Vm.RestoreSessionLogPanel.superclass.constructor.call(this, cfg);
    },

    initComponent: function () {
        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.emptyText = this.initialConfig.emptyText;

        this.bbar = new Ext.Toolbar({
            items: [{
                xtype: 'button',
                iconCls: 'x-refresh',
                cls: 'x-btn-gray',
                handler: function (b, e) {
                    this.fireEvent('reloadlog');
                },
                scope: this
            }]
        });


        Veeam.Vm.RestoreSessionLogPanel.superclass.initComponent.apply(this, arguments);
        this.addEvents('reloadlog');
    },

    reloadLog: function (data) {
        if (data)
            this.detailsPnTmpl.overwrite(this.body, data);
        else
            this.body.dom.innerHTML = this.emptyText;

    }
});