﻿Ext.ns('Veeam.Search');

Veeam.Search.FLR_DENIED_MESSAGE = "This file cannot be restored: backup file is missing.";
Veeam.Search.SEARCHRESULTS_LOADER_SRC = '/css/images/loader_big.gif';

Ext.ns('Veeam.Search.Model');

Veeam.Search.Model.Oib = Ext.data.Record.create([
    { name: 'OibId' },
    { name: 'BackupDate'},
    { name: 'BackupDate_TS' }
]);


Veeam.Search.Model.VmBrowseRequest = Ext.data.Record.create([
    { name: 'vmName' },
    { name: 'restorePoint_oibId',  mapping: 'restorePoint.m_oibId' },
    { name: 'restorePoint_backupDate', mapping: 'restorePoint.m_backupDate', type: 'int'},
    { name: 'folderPath'},
    { name: 'fileNamePattern'}
]);

Veeam.Search.Model.VmFileSearchRequest = Ext.data.Record.create([
    'q', 'vmfolder',
    { name: 'rb_doctype', type: 'int'},
    { name: 'rb_owner', type: 'int'},
    { name: 'rb_location', type: 'int'},
    'doctype', 'doctype_ext', 'author',
    { name: 'rb_lmt', type: 'int'},
    { name: 'lmt_datetype', type: 'int'},
    { name: 'lmt_from', type: 'int'},
    { name: 'lmt_to', type: 'int'},
    { name: 'rb_size',type: 'int'},
    { name: 'sizetype', type: 'int'},
    { name: 'size_from', type: 'int'},
    { name: 'size_to', type: 'int'},
    { name: 'size_opt_to', type: 'int'},
    { name: 'size_opt_from', type: 'int'},
    { name: 'rb_btime', type: 'int'},
    { name: 'btime_from', type: 'int'},
    { name: 'btime_to', type: 'int'},
    { name: 'bimported', type: 'bool' },
    { name: 'vm_vmRealName', mapping: 'vm.vmRealName'},
    { name: 'vm_vmDisplayName', mapping: 'vm.vmDisplayName'},
    { name: 'vm_userInput', mapping: 'vm.userInput'}
]);


Veeam.Search.Model.FileSearchResult = Ext.data.Record.create(
    [
            { name: 'id', convert: function (v, record) {
                return String.format("{0}_{1}", record.m_restorePoint.m_oibId, record.m_backedUpPath);
            } },
            'm_backedUpPath',
            { name: 'm_modified', type: 'date', dateFormat: 'timestamp' },
            { name: 'm_vmName' /*, mapping: 'm_vmName.vmDisplayName'*/ },
            'm_fileOwnerName', 'm_fileSizeHum',
            { name: 'm_oibId', mapping: 'm_restorePoint.m_oibId' },
            { name: 'm_backupDate', mapping: 'm_restorePoint.m_backupDate', type: 'date', dateFormat: 'timestamp' },
            'm_isOibRegistered', 'm_fileSize', 'status'
    ]
);


//public string vmname;
//        public string q;
//        public string vmfolder;
//        public int rb_doctype = 0;
//        public int rb_owner = 0;
//        public int rb_location = 0;
//        public String doctype;
//        public string doctype_ext;
//        public string author;
//        public int rb_lmt = 0;
//        public int lmt_datetype = 0;
//        public double lmt_from;
//        public double lmt_to;
//        public int rb_size = 0;
//        public int sizetype = 0;
//        public int size_from = 0;
//        public int size_to = 0;
//        public int size_opt_to = 0;
//        public int size_opt_from = 0;
//        public int rb_btime = 0;
//        public double btime_from;
//        public double btime_to;
//        public bool bimported = false;
//        public VmSearchResultJson vm;

// VM selection window
Veeam.Search.Model.VMSearchResult = Ext.data.Record.create([
    'vmFolderName',
    'vmRealName',
    'vmDisplayName', 
    { name: 'platform', type: 'int', defaultValue: 0 }
]);


Veeam.VmSpinner = function (cnf) {
    var c = cnf || {};
    //c = Ext.applyIf( c, {});    

    Veeam.VmSpinner.superclass.constructor.apply(this, [c]);
}

Ext.extend(Veeam.VmSpinner, Ext.form.SpinnerField, {
    forceWidth: function (w) { this.wrap.setWidth(w); this.el.setWidth(w - 17); }
});

Ext.reg('vm.ui.spinnerfield', Veeam.VmSpinner);  

Veeam.Search.CommonPanel = Ext.extend(Ext.Panel, {
    showMsg: function (result) {
        if (this.loadMask) this.loadMask.hide();
        Ext.MessageBox.show({ title: 'Veeam Backup Enterprise Manager',
            msg: result.message || (result.success ? 'Success.' : 'Fail.'),
            width: 400,
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox[result.success ? "INFO" : result.expired ? "WARNING" : "ERROR"]
        });
    }
});


Veeam.Search.DataField = Ext.extend(Ext.form.TriggerField, {
    displayProperty: null,
    createObjectFunction: Ext.emptyFn(),

    initComponent: function () {
        Ext.apply(this, {
            msgTarget: 'under',
            triggerClass: 'x-form-search-trigger'
        });

        Veeam.Search.DataField.superclass.initComponent.call(this);

        this.on('specialkey', function (f, e) {
            if (e.getKey() == e.ENTER) {
                e.stopEvent();
                this.onBlur();
                this.onTriggerClick();

            }
        }, this);
    },
    initValue: function () {

        this.object = this.initialConfig.valueObject || {};
        if (this.initialConfig.value)
            this.object = this.createUserInputObject(this.initialConfig.value);
        Veeam.Search.DataField.superclass.initValue.call(this);
    },

    setValue: function (v) {
        var o = v;
        if (typeof v == 'string') {
            // create user input object
            o = this.createUserInputObject(v);
        }
        this.object = o;
        //console.log('setValue: %s', o);
        Veeam.Search.DataField.superclass.setValue.call(this, this.object[this.displayProperty]);
    },
    getValue: function () {
        Veeam.Search.DataField.superclass.getValue.call(this);
        //console.log('getValue');
        return this.object[this.displayProperty] || "";
    },
    setRawValue: function (v) {
        var o = v;
        if (typeof v == 'string') {
            // create user input object
            o = this.createUserInputObject(v);
        }
        this.object = o;
        //console.log('setRawValue: %s', o);
        Veeam.Search.DataField.superclass.setRawValue.call(this, this.object[this.displayProperty]);
    },
    getRawValue: function () {
        //console.log('getRawValue');
        Veeam.Search.DataField.superclass.getRawValue.call(this);
        return this.object[this.displayProperty] || "";
    },

    createUserInputObject: function (userInputText) {
        //console.log('create userinput object: %s', userInputText);
        return this.createObjectFunction(userInputText);
    },
    onFocus: function () {
        this.preFocus();
        if (this.focusClass) {
            this.el.addClass(this.focusClass);
        }
        if (!this.hasFocus) {
            this.hasFocus = true;
            this.startValue = Veeam.Search.DataField.superclass.getValue.call(this);
            this.fireEvent('focus', this);
        }
    },
    onBlur: function () {
        this.beforeBlur();
        if (this.focusClass) {
            this.el.removeClass(this.focusClass);
        }
        this.hasFocus = false;
        if (this.validationEvent !== false && (this.validateOnBlur || this.validationEvent == 'blur')) {
            this.validate();
        }
        var v = Veeam.Search.DataField.superclass.getValue.call(this);

        if (String(v) !== String(this.startValue)) {
            var o = this.createUserInputObject(v),
                startO = this.getValue();

            if (!this.isEqualValues(o, startO)) {
                this.fireEvent('change', this, o, startO);
                this.setValue(o);
            }
        }
        this.fireEvent('blur', this);
        this.postBlur();
    },
    isEqualValues: function (newObj, oldObj) {

        var equal = oldObj != null && newObj[this.displayProperty] == oldObj[this.displayProperty];
        //console.log("objObj %o, newObj %o, equal: %s", oldObj, newObj, equal);
        return equal;
    },
    getValueObject: function () {
        return this.object;
    },

    showLoading: function(){
        this.wrap.addClass('loading-indicator');
        this.el.setWidth( this.el.getWidth() - 30); //indicator padding and margin
    },

    hideLoading: function(){
        this.wrap.removeClass('loading-indicator');
        this.el.setWidth( this.wrap.getWidth() -  this.trigger.getWidth());
    }

});


Veeam.Search.QuickSearchField = Ext.extend(Ext.form.TriggerField, {
    initComponent: function () {
        Veeam.Search.QuickSearchField.superclass.initComponent.call(this);
        this.on('specialkey', function (f, e) {
            if (e.getKey() == e.ENTER) {
                this.onTriggerClick();
            }
        }, this);
    },

    initEvents: function () {
        Veeam.Search.QuickSearchField.superclass.initEvents.call(this);
        this.addEvents('submit'); // add submit event
        this.addEvents('beforesubmit');
    },

    validationEvent: false,
    validateOnBlur: false,
    triggerClass: 'x-form-search-trigger',
    labelSeparator: '',
    width: 180,

    onTriggerClick: function () {
        var v = this.getValue();
        if (this.fireEvent('beforesubmit', this, v) !== false) {
            this.fireEvent('submit', this, v);
        }

    }
});

Ext.ns('Veeam.Search.ExtendedInfo');

Veeam.Search.ExtendedInfo.OnlineBackupGrid = Ext.extend(Ext.grid.GridPanel, {
    initComponent: function () {
        this.data = this.initialConfig.data || {};

        this.gridStore = new Ext.data.JsonStore({
            root: "m_regServers",
            fields: ['m_backupServerName', 'm_backupName'],
            data: this.data
        });

        Ext.apply(this, {
            anchor: '100%',
            store: this.gridStore,
            enableHdMenu: false,
            enableColumnHide: false,
            columns: [
                { id: 'backupServerName', header: "Backup Server", width: 150, dataIndex: 'm_backupServerName' },
                { id: 'jobName', header: "Backup Name", dataIndex: 'm_backupName' }
            ],
            title: 'File can be restored from the following backups:',
            iconCls: 'icon-grid',
            autoExpandColumn: 'jobName',
            boxMinHeight: 200,
            height: 230
        });
        Veeam.Search.ExtendedInfo.OnlineBackupGrid.superclass.initComponent.call(this);
    }
});


Veeam.Search.ExtendedInfo.OfflineBackupGrid = Ext.extend(Ext.grid.GridPanel, {
    initComponent: function () {
        this.data = this.initialConfig.data || {};
        this.gridStore = new Ext.data.GroupingStore({
            groupField: 'm_Title',
            reader: new Ext.data.JsonReader({
                root: "m_requiredFiles",
                fields: [
                  'm_Title',
                  'oibOrigins',
                  'm_server',
                  'm_backupServer',
                  'm_fileName',
                  { name: "m_backupDate", type: 'date', dateFormat: 'timestamp' },
                  'setIdx'
                ]
            }),
            sortInfo: { field: 'm_fileName', direction: "ASC" },
            data: this.data
        });

        Ext.apply(this, {
            anchor: '100%',
            store: this.gridStore,
            enableHdMenu: false,
            enableColumnHide: false,
            autoExpandColumn: 'fileName',
            columns: [
                { id: 'server', header: "Server", dataIndex: 'm_server', width: 100 },
                { id: 'fileName', header: "File Name", dataIndex: 'm_fileName', width: 150 },
                { header: "Date", dataIndex: "m_backupDate", width: 78, renderer: Ext.util.Format.dateRenderer(Veeam.Defaults.dtFormat) },
                { id: "m_Title", dataIndex: "m_Title", hidden: true }
            ],
            view: new Ext.grid.GroupingView({
                forceFit: true,
                showGroupName: false,
                startCollapsed: true,
                autoFill: true
            }),
            title: 'The following files are required to import backup:',
            iconCls: 'icon-grid',
            boxMinHeight: 200,
            height: 230
        });

        Veeam.Search.ExtendedInfo.OfflineBackupGrid.superclass.initComponent.call(this);
    }
});


Veeam.Search.ExtendedInfo.TapesBackupGrid = Ext.extend(Ext.grid.GridPanel, {
    initComponent: function () {
        this.data = this.initialConfig.data || {};
        this.gridStore = new Ext.data.GroupingStore({
            groupField: 'fileSet',
            reader: new Ext.data.JsonReader({
                root: "requiredTapes",
                fields: ['fileSet', 'backupFileName', 'mediaInfo', 'setIdx']

            }),
            sortInfo: { field: 'backupFileName', direction: "ASC" },
            data: this.data
        });
        Ext.apply(this, {
            anchor: '100%',
            store: this.gridStore,
            enableHdMenu: false,
            enableColumnHide: false,
            columns: [
                { id: 'file-id', header: "File", dataIndex: 'backupFileName', width: 150 },
                { id: 'mediaInfo-id', header: "Tapes", dataIndex: 'mediaInfo' },
                { id: 'fileSet-id', dataIndex: 'fileSet', hidden: true }
            ],
            view: new Ext.grid.GroupingView({
                forceFit: true,
                showGroupName: false,
                startCollapsed: true,
                autoFill: true
            }),
            title: 'File can be restored from the following media:',
            iconCls: 'icon-grid',
            autoExpandColumn: 'file-id',
            boxMinHeight: 200,
            height: 230
        });
        Veeam.Search.ExtendedInfo.TapesBackupGrid.superclass.initComponent.call(this);
    }
});

// Extender result view 
Veeam.Search.ExtendedInfoWindow = function (config) {
    var c = config || {};

    this.data = c.data;
    var items = this.buildItems(),
        title = this.buildTitle();

    c = Ext.apply({
        title: title,
        modal: true,
        id: "extended-info",
        width: 550,
        items: items,
        closable: true,
        resizable: true,
        boxMinHeigh: 400,
        autoScroll: true,
        stateful: false,
        buttons: [
            { text: 'Print', handler: this.printHandler, scope: this },
            { text: 'OK', handler: this.close, scope: this }
        ],
        buttonAlign: 'right'
    }, c);

    Veeam.Search.ExtendedInfoWindow.superclass.constructor.apply(this, [c]);
};



Ext.extend(Veeam.Search.ExtendedInfoWindow, Veeam.Window, {
    initComponent: function () {
        Veeam.Search.ExtendedInfoWindow.superclass.initComponent.apply(this, [arguments]);
        // this.addListener( 'show', this.showHandler, this, {single: true });

        this.activateGrid();
        this.activeGrid.on('viewready', this.showHandler, this, { single: true });
    },

    buildTitle: function () {
        return Ext.util.Format.ellipsis(this.data.record.m_fileName, 45, true);
    },

    buildGrid: function (type) {
        if (type == 'online')
            return new Veeam.Search.ExtendedInfo.OnlineBackupGrid({ data: this.data.info });
        else if (type == 'offline')
            return new Veeam.Search.ExtendedInfo.OfflineBackupGrid({ data: this.data.info });
        else if (type == "tapes")
            return new Veeam.Search.ExtendedInfo.TapesBackupGrid({ data: this.data.info });
        else
            throw Error("Unknown grid type: " + type);
    },


    buildItems: function () {
        this.recordArea = new Ext.Container({
            layout: 'fit',
            cls: 'result-extended',
            html: this.renderExtended(this.data)
        });

        this.messageArea = new Ext.Container({
            layout: 'fit',
            cls: 'mt10',
            autoHeight: true,
            hidden: this.data.info.isAbsent ? false : true,
            html: this.data.info.message
        });

        this.gridArea = new Ext.Container({
            layout: 'anchor',
            anchor: '100%',
            border: false,
            id: 'x-extended-grid-container',
            autoHeight: true
        });


        return [this.recordArea, this.gridArea, this.messageArea];
    },

    activateGrid: function () {
        var cnf = this.initialConfig.data.info;
        if (cnf.m_isOibRegistered === true) {
            this.activeGrid = this.buildGrid('online');
        } else {
            if (cnf.requiredTapes && cnf.requiredTapes.length > 0) {
                this.activeGrid = this.buildGrid('tapes');
                this.gridArea.add(this.activeGrid);
                if (cnf.filesSetCount < 2) {
                    this.activeGrid.gridStore.clearGrouping();
                    this.activeGrid.gridStore.fireEvent('groupchange', this.activeGrid.view, null);
                }
            } else {
                this.activeGrid = this.buildGrid('offline');
                this.gridArea.add(this.activeGrid);
                // enable/disable grouping
                if (cnf.filesSetCount < 2) {
                    this.activeGrid.gridStore.clearGrouping();
                    this.activeGrid.gridStore.fireEvent('groupchange', this.activeGrid.view, null);
                }
            }
        }

        this.gridArea.add(this.activeGrid);
        this.gridArea.doLayout();
    },

    showHandler: function () {
        if (this.activeGrid && this.activeGrid.gridStore instanceof Ext.data.GroupingStore) {
            var view = this.activeGrid.getView(),
                    store = this.activeGrid.gridStore,
                    firstRec = store.getAt(0);
            if (!firstRec)
                return;

            var groupField = store.groupField;

            if (groupField === false)
                return;
            var firstTitle = firstRec.get(groupField),
                    firstGroupId = view.getGroupId(firstTitle);
            view.toggleGroup(firstGroupId, true);
        }
    },
    printHandler: function () {
        if (this.activeGrid) {
            var html;
            if (this.recordArea) {
                html = this.recordArea.el.dom.innerHTML;
            }
            Ext.ux.GridPrinter.print(this.activeGrid, { html: html, position: 'before' });
            return false;
        }
    },
    renderExtended: function(cnf){
        return '<div class="group"><strong>File:</strong><br />' +
        '<div>' + cnf.record.m_backedUpPath + '</div>' +
        '<div class="lastmod"><span>Last modified:</span>' + /*cnf.record.m_modifiedHum*/ new Date(cnf.record.m_modified * 1000).format(Veeam.Defaults.dtFormat) + '</div>' +
        '<div class="size"><span>Size:</span>' + cnf.record.m_fileSizeHum + '</div>' +
        //'<div class="ownerName"><span>Owner:</span>' +  cnf.record.m_fileOwnerName + '</div>' +
        '</div>' +
        '<div class="group"><strong>VM:</strong><br />' +
        '<div class="name">' + cnf.record.m_vmName.vmDisplayName + (cnf.record.m_fileOwnerName ? ' ('  + cnf.record.m_fileOwnerName  + ')' : '' ) +
        '</div>' +
        '</div>' +
        '<div class="group"><strong>Restore point:</strong><br />' +
        '<div class="restore">' + /*cnf.record.m_restorePoint.m_backupDateHum */ new Date(cnf.record.m_restorePoint.m_backupDate * 1000).format(Veeam.Defaults.dtFormat) + '</div>' +
        '</div>'
    }

});


// Create subclass of Ext.form.fieldset with default params
Veeam.Search.SearchFieldset = function(cnf){
    var c = cnf || {};
    c = Ext.applyIf( c, {
        hideLabels: true,
        autoHeight: true,
        forceLayout: true,
        frame: false,
        cls: 'veeam-fieldset',
        defaults: { cellCls: "p3", stateful  : false }, // add extra spacing
        layout: 'table', // 2 columns table layout
        layoutConfig: { columns: 2 },
        listeners: {
            afterlayout: function(){
             // fix combobox width
             var items = this.items.items;
             for (var i=0, len = items.length; i<len; i++){
               if (typeof(items[i].forceWidth) != 'undefined'){
                   if (items[i].width) { items[i].forceWidth( items[i].width ); }
                }
             }
            }
        }
    });

    Veeam.Search.SearchFieldset.superclass.constructor.apply(this, [c]);
}

Ext.extend(Veeam.Search.SearchFieldset, Ext.form.FieldSet, {});
Ext.reg('vm.ui.searchfieldset', Veeam.Search.SearchFieldset);




