Ext.define('CurrentVariableModel', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'name', type: 'string'},
        {name: 'value', type: 'string'},
        {name: 'id', type: 'string'}
    ]
});

Ext.define('VariableMonitor', {
    constructor: function(){
        this.LastX = Ext.Element.getViewportWidth() - 500;
        this.LastY = 0;
        this.CurrentVariablesStore = Ext.create('Ext.data.Store', {
            model: 'CurrentVariableModel'
        });
        this.ShownOnce = false;
        var initVarlist = ["ELEMENTNAME", "SCORE", "ANSWER", "CORRECTANSWER"];
        Ext.Array.forEach(initVarlist, function (v) {
            var theVar = Author.VariableManager.getVariableByName(v);
            var aVar = Ext.create('CurrentVariableModel', {
                name: theVar.Name,
                value: '',
                id: theVar.id
            });
            this.CurrentVariablesStore.add(aVar);
        }, this);


        this.AllVariablesArray = new Array();
        Author.VariableManager.Variables.each(function(variable, index, length){
            this.AllVariablesArray.push(
                variable.Name
            );
        }, this);
        this.VariableGrid = Ext.create('Ext.grid.Panel', {
            store: this.CurrentVariablesStore,
            itemId: 'grid',
            plugins: [
                Ext.create('Ext.grid.plugin.CellEditing', {
                    clicksToEdit: 2,
                    listeners: {
                        beforeedit: function(e, eOpts){
                            if (e.field == "value") {
                                var vID = e.record.get('id');
                                var theVar = Author.VariableManager.getVariableByID(vID);
                                return  !(theVar && theVar.IsReadOnly);
                            }
                        },
                        edit: function(editor, e, eopts){
                            if (e.field == "value") {
                                var vName = e.record.get('name');
                                var theVar = Author.VariableManager.getVariableByName(vName);
                                if (theVar) {
                                    theVar.setValue(e.record.get('value'));
                                    e.record.set('id', theVar.id);
                                    e.record.set('name', theVar.Name);
                                    e.record.set('value', theVar.getValue());
                                }
                                e.record.commit();
                            }
                            if (e.field == 'name') {
                                this.updateRecord(e.record);
                            }
                        },
                        scope: this
                    }
                })
            ],
            columns: [
                {
                    header: 'Variable',
                    dataIndex: 'name',
                    width: 150,
                    align: 'center',
                    sortable: true,
                    editor: {
                        xtype: 'combobox',
                        typeAhead: true,
                        triggerAction: 'all',
                        selectOnTab: true,
                        store: this.AllVariablesArray
                    },
                    menuDisabled: true
                },
                {
                    header: 'Value',
                    dataIndex: 'value',
                    flex: 1,
                    editor: {
                        xtype: 'textfield',
                        allowBlank: true
                    },
                    align: 'center',
                    sortable: false,
                    menuDisabled: true
                }
            ],
            dockedItems: [
                {
                    xtype: 'toolbar',
                    dock: 'top',
                    itemId: 'topBar',
                    items: [
                        {
                            xtype: 'button',
                            text: 'Add Watch',
                            icon: './lib/images/add.gif',
                            listeners: {
                                click: function(e){
                                    var lastItem = this.CurrentVariablesStore.last();
                                    
                                    if(lastItem.data.id !== "-1" || this.CurrentVariablesStore.count() === 0)//Without this check you can keep on clicking this and adding useless cells
                                    {
                                        var aVar = Ext.create('CurrentVariableModel', {
                                            name: "",
                                            value: "",
                                            id: "-1"
                                        });
                                        this.CurrentVariablesStore.add(aVar);
                                    }

                                    this.VariableGrid.editingPlugin.startEdit(this.CurrentVariablesStore.count() - 1, 0);
                                },
                                scope: this
                            }
                        },
                        {
                            xtype: 'button',
                            itemId: 'removeBtn',
                            icon: './lib/images/delete.gif',
                            text: 'Remove Watch',
                            disabled: true,
                            listeners: {
                                click: function(){
                                    //this.VariableGrid.stopEditing();
                                    var s = this.VariableGrid.getSelectionModel().getSelection();
                                    for (var i = 0, r; r = s[i]; i++) {
                                        this.CurrentVariablesStore.remove(r);
                                    }
                                },
                                scope: this
                            }
                        },
                        {
                            icon: './lib/images/refresh.gif',
                            text: 'refresh',
                            listeners: {
                                click: function(){
                                    this.refreshVariableValues();
                                },
                                scope: this
                            }
                        }
                    ]
                }
            ],
            selModel: {
                mode: 'MULTI',
                allowDeselect: true
            },
            listeners: {
                selectionchange: function(selectionMode, selected, eOpts){
                    this.VariableGrid.getDockedComponent('topBar').getComponent('removeBtn').setDisabled(selected.length < 1);
                },
                scope: this
            }
        });
        this.VariableMonitorWindow = new Ext.Window({
            title: 'Variable Watch',
            id: 'VariableWatchWindow',
            layout: 'fit',
            width: 500,
            height: 200,
            minWidth: 360,
            collapseFirst: true,
            collapsible: true,
            closeAction: 'hide',
            items: this.VariableGrid,
            listeners: {
                hide: this.onHide,
                show: this.onShown,
                move: this.onMove,
                scope: this
            }
        });
    }, onMove: function(c, x, y){
        if(!this.ShownOnce) return;
        this.LastX = Math.max(x, 0);
        this.LastY = Math.max(y, 0);
    },
    onShown: function(){
        this.ShownOnce = true;
        this.VariableMonitorWindow.setPosition(this.LastX, this.LastY);
        this.refreshVariableValues();
    },
    onHide: function(){
    },
    show: function(){
        this.VariableMonitorWindow.show();
    },
    hide: function(){
        this.VariableMonitorWindow.hide();
    },
    isVisible: function(){
        return (this.VariableMonitorWindow.isVisible());
    },
    updateRecord: function(record){
        var vName = record.get('name');
        var theVar = Author.VariableManager.getVariableByName(vName);
        if (theVar) {
            record.set('id', theVar.id);
            record.set('name', theVar.Name);
            record.set('value', theVar.getValue());
        }
        record.commit();
    },
    refreshVariableValues: function(){
        this.VariableGrid.getStore().each(this.updateRecord, this);
    }
});

