﻿Ext.ns("Veeam.VCPlugin");

Veeam.VCPlugin.HOSTSTATUS = [
    'Ok',
    'Warning'
];
Veeam.VCPlugin.HOSTREMOVED_MESSAGE = 'vCenter Server was removed from backup management server.'


Veeam.VCPlugin.PLUGINSTATUS = [ 'Unknown', 'Not installed', 'Installed', 'Not supported', 'Pending...'];


Veeam.VCPlugin.Panel = Ext.extend(Veeam.ConfigurationTab, {
    initComponent: function () {

        var me = this;
        Ext.apply(me, {
            items: me.buildItemsConfig(),
            layout: 'fit',
            id: 'vcplugin-main-panel',
            border: false,
            frame: true,
            tbar: me.buildToolbar(),
            cls: 'x-veeam-grid'
        });

        this.userTaskManager = new Veeam.UserTaskManager({ updateInterval: 5000 });
        this.userTaskManager.addListener('taskcomplete', this.taskCompleteHandler, this);
        this.tasks = [];

        this.on('afterrender', this.initData, this, { single: true });
        Veeam.VCPlugin.Panel.superclass.initComponent.call(this);
    },
    buildItemsConfig: function () {
        this.grid = this.buildGrid();
        return [this.grid];
    },
    buildGrid: function () {

        var statusRenderer = function (dict) {
            return function (status, meta) {
                if (Veeam.VCPlugin.HOSTSTATUS == dict && 1 == status) {
                    meta.attr = 'qtip="' + Veeam.VCPlugin.HOSTREMOVED_MESSAGE + '"';
                }
                return dict[status] || '-';
            }
        };

        this.store = new Ext.data.JsonStore({
            autoDestroy: true,
            root: 'items',
            totalProperty: 'totalCount',
            remoteSort: true,
            autoLoad: false,
            sortInfo: {
                direction: 'ASC',
                field: 'vcName'
            },
            baseParams: {
                start: 0,
                limit: this.initialConfig.pageSize || 20
            },
            idProperty: 'vcId',
            fields: [
                     { name: 'vcName' },
                     { name: 'vcId' },
                     { name: 'vcVersion' },
                     { name: 'vcStatus' },
                     { name: 'pluginStatus' },
                     { name: 'pluginVersion' },
                     { name: 'pluginIntallBy' }
                ],
            proxy: new Veeam.RpcDataProxy({ method: 'vcplugin.getGridData' })
        });

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


        var cfg = {
            layout: 'fit',
            border: false,
            store: this.store,
            colModel: new Ext.grid.ColumnModel({
                defaults: {
                    width: 120,
                    sortable: true
                },
                columns: [
                    { header: 'vCenter Server', dataIndex: 'vcName' },
                     { header: 'vCenter Server Version', dataIndex: 'vcVersion' },
                     { header: 'vCenter Server Status', dataIndex: 'vcStatus', renderer: statusRenderer(Veeam.VCPlugin.HOSTSTATUS) },
                     { header: 'Plugin-in Status', dataIndex: 'pluginStatus', renderer: statusRenderer(Veeam.VCPlugin.PLUGINSTATUS) },
                     { header: 'Plugin-in Version', dataIndex: 'pluginVersion' },
                     { header: 'Installed by', dataIndex: 'pluginIntallBy' }
                ]
            }),
            viewConfig: {
                forceFit: true
            },
            sm: new Ext.grid.RowSelectionModel({ singleSelect: true })
        };
        return new Ext.grid.GridPanel(cfg);
    },
    buildToolbar: function () {
        var toolbar = new Ext.Toolbar({
            items: [
                { text: 'Refresh', iconCls: 'x-refresh', handler: this.refreshHandler, scope: this },
                '->',
                { text: 'Check version …', iconCls: 'x-button-gear', handler: this.checkPluginVersion, scope: this },
                { text: 'Install', iconCls: 'icon-tasks-addserver', handler: this.installPlugin, scope: this },
                { text: 'Remove', iconCls: 'icon-tasks-removeserver', handler: this.removePlugin, scope: this }
            ]
        });

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

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

    },

    storeReloadHandler: function (store, options) {
        var sm = this.grid.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;
    },

    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();
    },

    checkPluginVersion: function () {
        var id = this.getSelectedId();
        if (!id)
            return;
        var rpcCall = CommonDataHandler.rpc["vcplugin.checkHost"]({ 'id': id });
        rpcCall.callback = this.callbackHandler.createDelegate(this, [rpcCall.request], true);
        rpcCall.call(ext_channel);
        this.notify('Checking host');
    },

    getSelectedId: function () {
        var sm = this.grid.getSelectionModel();
        if (!sm.hasSelection())
            return;

        var r = sm.getSelections()[0],
            id = r.get('vcId');
        return id;
    },

    installPlugin: function () {
        var id = this.getSelectedId();
        if (!id)
            return;
        var rpcCall = CommonDataHandler.rpc["vcplugin.installPlugin"]({ 'id': id });
        rpcCall.callback = this.callbackHandler.createDelegate(this, [rpcCall.request], true);
        rpcCall.call(ext_channel);
        this.notify('Starting install');
    },

    removePlugin: function () {
        var id = this.getSelectedId();
        if (!id)
            return;

        return Ext.MessageBox.confirm("", "Remove vSphere Web Client plug-in?", function (btn) {
            if (btn == 'yes') {

                var rpcCall = CommonDataHandler.rpc["vcplugin.removePlugin"]({ 'id': id });
                rpcCall.callback = this.callbackHandler.createDelegate(this, [rpcCall.request], true);
                rpcCall.call(ext_channel);
                this.notify('Starting uninstall');
            }

        }, this)

    },

    callbackHandler: function (result, rpcCall) {
        if (result.success === false) {
            if (result.request) {
                // Credentials callback
                Ext.MessageBox.hide();
                var cw = new Veeam.VCPlugin.CredentialWindow({
                    errorMessage: result.message,
                    listeners: { commit: this.credentialCallback.createDelegate(this, [rpcCall], true) }
                });
                cw.show();
                return;
            } else {
                return Veeam.Msg.error({ msg: result.message });
            }
        }
        var taskId = result.message;
        this.tasks.push(taskId);
        this.userTaskManager.addTask({ id: taskId, type: Veeam.UserTaskTypes.VcPlugin });

        var recId = rpcCall.params[0]["id"];
        if (recId) {
            var r = this.store.getById(recId);
            r && r.set('pluginStatus', 4);
        }

    },

    credentialCallback: function (w, request) {
        if (w) {
            var origParams = request.params[0];

            var params = Ext.apply({
                creds: w.captureData()
            }, origParams);
        }
        var rpc = CommonDataHandler.rpc[request.method](params);
        rpc.callback = this.callbackHandler.createDelegate(this, [rpc.request], true)
        rpc.call(ext_channel);

    },
    taskCompleteHandler: function (updater, taskResult) {
        if (this.tasks.indexOf(taskResult.id) != -1) {
            this.tasks.remove(taskResult.id);
            if (Veeam.UserTaskResult.ERROR == taskResult.state) {
                Veeam.Msg.error({ msg: taskResult.resultMessage });
            }
            this.refreshHandler.call(this);
        }
    },
    notify: function (message) {
        var notification = Veeam.Notification(message);
        if (notification)
            notification.show();
    }
});

Ext.reg('veeam.ui.vcplugin.panel', Veeam.VCPlugin.Panel);



Veeam.VCPlugin.CredentialWindow = Ext.extend(Ext.Window, {
    initComponent: function () {
        Ext.apply(this, {
            title: 'Web Client Plug-in',
            items: this.buildBody(),
            modal: true,
            width: 365,
            cls: 'credentials-window',
            bodyCssClass: 'x-white-body',
            closable: true,
            resizable: false,
            buttons: this.buildButtons(),
            border: false,
            keys: [{ key: 13, fn: this.okHandler, scope: this}]
        });

        this.addEvents(['commit']);

        Veeam.VCPlugin.CredentialWindow.superclass.initComponent.call(this);
    },
    buildBody: function () {
        this.errorMessage = new Ext.form.DisplayField({
            value: this.initialConfig.errorMessage,
            hideLabel: true,
            anchor: '100%',
            cls: 'x-field-error'
        });

        this.username = new Ext.form.TextField({
            fieldLabel: 'Username',
            anchor: '100%'
        });
        this.password = new Ext.form.TextField({
            fieldLabel: 'Password',
            inputType: 'password',
            anchor: '100%'
        });

        this.port = new Ext.form.NumberField({
            allowBlank: false,
            fieldLabel: 'Port',
            width: 50,
            value: 443,
            allowNegative: false
        });

        this.pn = new Ext.Container({
            layout: 'column',
            items: [
                {
                    xtype: 'box', cls: 'x-bg-keys', width: 80
                },
                {
                    xtype: 'container',
                    columnWidth: 1,
                    layout: 'form',
                    items: [
                        this.username,
                        this.password,
                        this.port,
                        this.errorMessage
                    ]
                }
            ]

        });

        return [
            {
                xtype: 'container', cls: 'x-white-body-inner', items: [
                {
                    xtype: 'box', anchor: '100%', height: 24, layout: 'anchor', cls: 'x-form-item', html: 'Specify vCenter Server connection account:'
                },
                    this.pn
              ]
            }
        ];

    },

    buildButtons: function () {
        return [
            new Ext.Button({ text: this.initialConfig.okText || 'OK', handler: this.okHandler, scope: this }),
            new Ext.Button({ text: 'Cancel', handler: this.close, scope: this })
        ]
    },

    captureData: function () {
        return {
            'username': this.username.getValue(),
            'password': this.password.getValue(),
            'port': this.port.getValue()
        };
    },

    okHandler: function () {
        if (this.fireEvent('commit', this) !== false)
            this.close();
    }

});

