/**
 * Project       AMDA-NG
 * Name          StatisticsUI.js
 * @class 	 amdaUI.statisticsUI
 * @extends      Ext.container.Container
 * @brief	 Statistics Module UI definition (View)
 * @author 	 elena
 */

Ext.define('amdaUI.StatisticsUI',
        {
            extend: 'Ext.container.Container',
            alias: 'widget.panelStatistics',

            requires: [
                //'amdaModel.Function'
                'amdaUI.TimeSelectorUI',
                'amdaUI.ParamArgumentsPlug',
                'amdaModel.DownloadParam',
                'amdaModel.RequestParamObject'
            ],

            statics:
                    {
                        //	  functionStore : null
                    },

            constructor: function (config)
            {
                this.init(config);
                this.callParent(arguments);
                this.loadObject();

                var paramArgsPlug = this.getPlugin('statistics-param-arguments-plugin');
                if (paramArgsPlug)
                    paramArgsPlug.onApply = this.onApplyParameterArgs;
            },

            loadObject: function ()
            {
                // load object into form	
                var basicForm = this.formPanel.items.items[1].getForm();
                basicForm.loadRecord(this.object);

            },

            onApplyParameterArgs: function (parentUI, paramObject)
            {
                parentUI.paramGrid.getView().refresh();
            },

            addParam: function (paramId, isLeaf, needArgs, components)
            {
                // adding the parameter to the  paramGrid
                var paramObj = amdaModel.RequestParamObject.getEmptyObj();
                paramObj.paramid = paramId;

                if (components) {
                    if (components['index1']) {
                        paramObj['dim1-index'] = components['index1'];
                        ++paramObj['type'];
                    }

                    if (components['index2']) {
                        paramObj['dim2-index'] = components['index2'];
                        ++paramObj['type'];
                    }
                }

                var r = Ext.create('amdaModel.DownloadParam', paramObj);
                this.paramGrid.getStore().add(r);
                this.paramGrid.getSelectionModel().select(this.paramGrid.getStore().getCount() - 1);
                //	var pos = this.paramGrid.store.getCount();
                //	this.paramGrid.store.insert(pos,r); 
                this.paramGrid.getView().refresh();

                if (needArgs)
                    this.editParameterArgs(r);
            },

            editParameterArgs: function (record)
            {
                var paramArgsPlug = this.getPlugin('statistics-param-arguments-plugin');

                if (paramArgsPlug)
                    paramArgsPlug.show('statistics-param-arguments-plugin', record);
            },

            addTT: function (TTname, TTid)
            {
                this.timeSelector.addTT(TTname, TTid);
                ;
            },

            /**
             * Set Start-Stop from parameter info (Local & MyData)
             */
            setTimeFromData: function (obj) {
                if (!obj.start || !obj.stop)
                    return;

                var dateStart = new Date(obj.start.replace(/[T|Z]/g, ' ').replace(/\-/g, '\/'));
                var dateStop = new Date(obj.stop.replace(/[T|Z]/g, ' ').replace(/\-/g, '\/'));

                this.formPanel.items.items[1].getForm().setValues({startDate: dateStart, stopDate: dateStop});
                this.timeSelector.intervalSel.updateDuration();
            },

            generateCatalog: function ()
            {
                var module = myDesktopApp.getLoadedModule(myDesktopApp.dynamicModules.statistics.id);
                if (module)
                    module.linkedNode.execute();
            },

            /*
             * Update this.object from form
             */
            updateObject: function ()
            {
                // get the basic form of the left 
                var basicForm = this.formPanel.items.items[1].getForm();
                var updateStatus = true;
                var formValues = basicForm.getValues();
                this.object.set('name', this.fieldName.getValue());
                this.object.set('description', formValues.description);

                var recs = this.paramGrid.getStore().getNewRecords();
                var paramArr = new Array();

                Ext.Array.each(recs, function (rec, index, allItems)
                {
                    var obj = Ext.clone(rec.data);

                    if (obj.function == null)
                    {
                        myDesktopApp.warningMsg('Please select function : `click to select`');
                        updateStatus = false;
                        return;
                    }
                    paramArr.push(obj);
                });

                this.object.set('parameter', paramArr);

                var timeSource = this.timeSelector.getActiveTimeSource();

                if (timeSource === amdaModel.AmdaTimeObject.inputTimeSrc[0] // timeSource  'TimeTable'
                        && this.timeSelector.TTGrid.getStore().count() == 0)
                {
                    myDesktopApp.warningMsg('You\'ve chosen Time Selection `by TimeTable` but no timeTable was added!'
                            + '<br>You must add one or choose Time Selection `by Interval`');
                    return false;
                }

                basicForm.updateRecord(this.object);
                this.object.set('timesrc', timeSource);
                // set valid intervals into TimeTable object
                if (timeSource === amdaModel.AmdaTimeObject.inputTimeSrc[0])
                    this.object.set('timeTables', this.timeSelector.TTGrid.getStore().data.items);

                return updateStatus;
            },

            /**
             * Check if changes were made before closing window 
             * @return true if changes
             */
            fclose: function ()
            {
                if (this.status == null)
                    return false;

                var isDirty = this.formPanel.getForm().isDirty() || (this.status.isModified) || (this.status.nbModified > 0) || (this.status.nbNew > 0);
                return isDirty;
            },

            /**
             * View configuration
             */
            init: function (config)
            {
                this.fieldName = new Ext.form.field.Text({
                    fieldLabel: 'Catalog Name',
                    allowBlank: false,
                    stripCharsRe: /(^\s+|\s+$)/g,
                    emptyText: 'Please no spaces!',
                    name: 'name',
                    //	      anchor: '100%',
                    validateOnChange: false,
                    validateOnBlur: false,
                    validFlag: false,
                    validator: function () {
                        return this.validFlag;
                    }
                });

                var ttStore = Ext.create('Ext.data.Store',
                        {
                            fields: ['name', 'hidden_id']
                        });

                this.timeSelector = new amdaUI.TimeSelectorUI({id: 'statisticsTimeSelector', flex: 1});

                var store = Ext.create('Ext.data.Store',
                        {
                            fields: ['name', 'function']
                        });

                this.paramGrid = Ext.create('Ext.grid.Panel',
                        {
                            title: 'Select Parameter & Apply Function',
                            selType: 'rowmodel',
                            flex: 2,
                            //			height :250,
                            store: store,
                            columns: [
                                {xtype: 'rownumberer'},
                                {
                                    header: "Parameter Name",
                                    dataIndex: 'name',
                                    flex: 1,
                                    sortable: false,
                                    menuDisabled: true,
                                    renderer: function (val, meta, rec) {
                                        return rec.getParamFullName();
                                    }
                                },
                                //	{ header: 'parameter',  dataIndex: 'name', menuDisabled : true, sortable : false },
                                {header: 'function', dataIndex: 'function', menuDisabled: true, sortable: false,
                                    editor:
                                            {
                                                xtype: 'combo', queryMode: 'local',
                                                //emptyText : 'please click to select function',
                                                store: ['min', 'max', 'mean', 'RMS', 'median', 'variance', 'skewness', 'kurtosis', 'count', 'countNotNan', 'countTrue'],
                                                triggerAction: 'all',
                                                //lazyInit: false,
                                                listeners: {
                                                    focus: function (obj) {
                                                        obj.expand();
                                                    }
                                                }
                                            },
                                    renderer: function (v)
                                    {
                                        if (v != null && v.length > 0)
                                            return v;
                                        else
                                            return 'click to select';
                                    }
                                },
                                {menuDisabled: true, width: 30, renderer: function () {
                                        return '<div class="icon-remover" style="width: 15px; height: 15px;"></div>';
                                    }
                                }
                            ],
                            plugins: [Ext.create('Ext.grid.plugin.CellEditing', {clicksToEdit: 1})],
                            listeners:
                                    {
                                        render: function (o, op)
                                        {
                                            var me = this;
                                            var el = me.body.dom;
                                            var dropTarget = Ext.create('Ext.dd.DropTarget', el, {
                                                ddGroup: 'explorerTree',
                                                notifyOver: function (ddSource, e, data)
                                                {
                                                    if (data.records[0].data.nodeType == 'localParam' && data.records[0].get('notyet')) {
                                                        this.valid = false;
                                                        return this.dropNotAllowed;
                                                    }
                                                    if (((data.records[0].data.nodeType == 'localParam') ||
                                                            (data.records[0].data.nodeType == 'remoteParam') ||
                                                            (data.records[0].data.nodeType == 'remoteSimuParam') ||
                                                            (data.records[0].data.nodeType == 'derivedParam') ||
                                                            (data.records[0].data.nodeType == 'myDataParam') ||
                                                            (data.records[0].data.nodeType == 'alias')) &&
                                                            (data.records[0].isLeaf() || data.records[0].data.isParameter) &&
                                                            !data.records[0].data.disable)
                                                    {
                                                        this.valid = true;
                                                        return this.dropAllowed;
                                                    }

                                                    this.valid = false;
                                                    return this.dropNotAllowed;
                                                },
                                                notifyDrop: function (ddSource, e, data)
                                                {
                                                    if (!this.valid)
                                                        return false;
                                                    var nameToSent;
                                                    var components = null;

                                                    switch (data.records[0].data.nodeType)
                                                    {
                                                        case 'localParam' :
                                                        case 'remoteParam':
                                                        case 'remoteSimuParam':
                                                            nameToSent = data.records[0].get('id');
                                                            if (data.records[0].get('alias') != "")
                                                                var nameToSent = "#" + data.records[0].get('alias');
                                                            var component_info = data.records[0].get('component_info');
                                                            if (component_info && component_info.parentId)
                                                            {
                                                                if (component_info.index1 && component_info.index2)
                                                                {
                                                                    nameToSent = component_info.parentId;
                                                                    components = [];
                                                                    if (component_info.index1)
                                                                        components['index1'] = component_info.index1;
                                                                    if (component_info.index2)
                                                                        components['index2'] = component_info.index2;
                                                                }
                                                                if (data.records[0].get('needsArgs'))
                                                                {
                                                                    nameToSent = component_info.parentId;
                                                                    if (component_info.index1)
                                                                    {
                                                                        components = [];
                                                                        components['index1'] = component_info.index1;
                                                                    }
                                                                }
                                                            }
                                                            break;
                                                        case 'alias' :
                                                            nameToSent = "#" + data.records[0].get('text');
                                                            break;
                                                        case 'derivedParam' :
                                                            if (data.records[0].modelName == 'amdaModel.DerivedParamComponentNode')
                                                            {
                                                                paramId = data.records[0].get('text');
                                                                var parentId = paramId.substr(0, paramId.length - 3);
                                                                nameToSent = "ws_" + parentId;
                                                                var regExp = /\(([\d]+)\)/;
                                                                var component_index = regExp.exec(paramId);
                                                                if (component_index)
                                                                {
                                                                    components = [];
                                                                    components['index1'] = component_index[1];
                                                                }
                                                                break;
                                                            } else
                                                            {
                                                                nameToSent = "ws_" + data.records[0].get('text');
                                                            }
                                                            break;
                                                        case 'myDataParam' :
                                                              if (data.records[0].modelName == 'amdaModel.MyDataParamComponentNode')
                                                            {
                                                                paramId = data.records[0].get('text');
                                                                var parentId = paramId.substr(0, paramId.length - 3);
                                                                nameToSent = "wsd_" + parentId;
                                                                var regExp = /\(([\d]+)\)/;
                                                                var component_index = regExp.exec(paramId);
                                                                if (component_index)
                                                                {
                                                                    components = [];
                                                                    components['index1'] = component_index[1];
                                                                }
                                                                break;
                                                            } else{
                                                            nameToSent = "wsd_" + data.records[0].get('text');
                                                        }
                                                            break;
                                                        default :
                                                            return false;
                                                    }
                                                    var module = myDesktopApp.getLoadedModule(myDesktopApp.dynamicModules.statistics.id);
                                                    if (module)
                                                    {
                                                        module.addParam(nameToSent, data.records[0].get('leaf'), data.records[0].get('needsArgs'), components);
                                                    }
                                                    return true;
                                                }
                                            });
                                        },
                                        cellclick: function (grid, cell, cellIndex, record) {
                                            if (cellIndex == 3)
                                                grid.getStore().remove(record);
                                        }
                                    }
                        });


                this.formPanel = Ext.create('Ext.form.Panel',
                        {
                            region: 'center',
                            layout: {
                                type: 'hbox',
                                pack: 'start',
                                align: 'stretch'
                            },
                            defaults: {bodyStyle: {background: '#dfe8f6'}, padding: '3'},
                            fieldDefaults: {labelWidth: 80, labelAlign: 'top'},
                            items: [{
                                    xtype: 'form',
                                    flex: 1,
                                    layout: {type: 'vbox', pack: 'start', align: 'stretch'},
                                    items: [this.paramGrid],
                                    fbar: [{
                                            type: 'button',
                                            text: 'Generate Catalog',
                                            scope: this,
                                            handler: function ()
                                            {
                                                // update object with user's values
                                                // if the return is true (object had been updated)
                                                if (this.updateObject()) {
                                                    this.generateCatalog();
                                                }
                                            }
                                        },
                                        {
                                            type: 'button',
                                            text: 'Reset',
                                            scope: this,
                                            handler: function () {
                                                this.formPanel.getForm().reset();
                                                this.paramGrid.store.removeAll();
                                                this.timeSelector.TTGrid.store.removeAll();
                                            }
                                        }]
                                },
                                {
                                    xtype: 'form',
                                    title: 'Additional Information',
                                    flex: 1,
                                    trackResetOnLoad: true,
                                    layout: {type: 'vbox', pack: 'start', align: 'stretch', padding: '3'},
                                    items: [
                                        this.fieldName,
                                        {
                                            xtype: 'textarea',
                                            name: 'description',
                                            fieldLabel: 'Description',
                                            height: 125
                                        },
                                        this.timeSelector
                                    ]
                                }
                            ]
                        });

                var myConf = {
                    layout: 'border',
                    items: [
                        this.formPanel,
                        {
                            xtype: 'panel',
                            region: 'south',
                            title: 'Information',
                            collapsible: true,
                            collapseMode: 'header',
                            height: 160,
                            autoHide: false,
                            bodyStyle: 'padding:5px',
                            iconCls: 'icon-information',
                            loader: {
                                autoLoad: true,
                                url: helpDir + 'statisticsHOWTO'
                            }
                        }],
                    plugins: [{ptype: 'paramArgumentsPlugin', pluginId: 'statistics-param-arguments-plugin'}]
                };

                Ext.apply(this, Ext.apply(arguments, myConf));
            }
        });