/**
* Project AMDA-NG
* Name CatalogUI.js
* @class amdaUI.catalogUI
* @extends Ext.container.Container
* @brief Catalog Module UI definition (View)
* @author elena
*/
Ext.define('amdaUI.CatalogUI', {
extend: 'Ext.container.Container',
alias: 'widget.panelCatalog',
requires: [
'Ext.grid.plugin.BufferedRenderer'
],
isCatalog : true,
constructor: function(config) {
this.init(config);
this.callParent(arguments);
this.toReconfigure = true;
if (this.object) this.loadObject();
},
setObject : function (object, toReconfigure) {
if (toReconfigure)
this.toReconfigure = true;
// set object
this.object = object;
// load object into view
this.loadObject();
},
/**
* set params description into this.object
*/
setParamInfo : function(parameters) {
var params = [];
Ext.Array.each(parameters, function(item, index) {
params[index] = item;
}, this);
this.object.set('parameters', params);
},
/**
* update this.object from form
*/
updateObject : function(){
// get the basic form
var basicForm = this.formPanel.getForm();
var updateStatus = true;
var fieldsWithoutName = basicForm.getFields().items;
Ext.Array.each(fieldsWithoutName, function(item, index,allItems){
if(item !== this.fieldName) {
if (!item.isValid()) {
// set update isn't allowed
updateStatus = false;
}
}
}, this);
// if the update is allowed
if (updateStatus) {
/// real object update
// update TimeTable object with the content of form
basicForm.updateRecord(this.object);
}
// return the update status
return updateStatus;
},
updateCount : function() {
this.object.set('nbIntervals',this.TTGrid.getStore().getTotalCount());
this.formPanel.getForm().findField('nbIntervals').setValue(this.object.get('nbIntervals'));
},
onAfterInit: function(result, e)
{
var me = this;
if (!result) {
myDesktopApp.errorMsg(e.message);
Ext.defer(function(){Ext.Msg.toFront()},10);
return;
}
else if (!result.success)
{
if (result.message)
myDesktopApp.errorMsg(result.message);
else
myDesktopApp.errorMsg('Unknown error during catalog cache initialisation');
Ext.defer(function(){Ext.Msg.toFront()},10);
return;
}
if (me.toReconfigure)
{
var fields = [], columns = [], i = 3, width, index;
var fieldsConfig = [{ name : 'start' },{ name : 'stop' },{ name: 'cacheId', type : 'int'},
{ name: 'isNew', type : 'boolean', defaultValue: false },
{ name: 'isModified', type : 'boolean', defaultValue: false}
];
for (var j = 0; j < 5; j++) fields[j] = Ext.create('Ext.data.Field', fieldsConfig[j]);
columns[0] = Ext.create('Ext.grid.column.RowNumberer');
columns[1] = Ext.create('Ext.grid.column.Column', { text: 'Start Time', sortable : false, dataIndex: 'start',
width : 120, menuDisabled: true, editor : { xtype:'datefield', allowBlank:false, hideTrigger: true, format : 'Y-m-d\\TH:i:s'}});
columns[2] = Ext.create('Ext.grid.column.Column', { text: 'Stop Time', sortable : false, dataIndex: 'stop',
width : 120, menuDisabled: true, editor : { xtype:'datefield', allowBlank:false, hideTrigger: true, format : 'Y-m-d\\TH:i:s'}});
Ext.Array.each(result.parameters, function(obj)
{
index = 'param'+(i-1).toString();
fields[i+2] = Ext.create('Ext.data.Field',{ name : index });
if (obj.type == 1) // dateTime
{
columns[i] = Ext.create('Ext.grid.column.Column', { text: obj.name, sortable : false, dataIndex: index,
width : 120, menuDisabled: true, editor : { xtype:'datefield', allowBlank:false, hideTrigger: true, format : 'Y-m-d\\TH:i:s'}});
}
else
{
width = 50. * parseInt(obj.size);
columns[i] = Ext.create('Ext.grid.column.Column', { text: obj.name, sortable : false, dataIndex: index,
width : width, menuDisabled: true, editor: 'textfield' });
}
i++;
});
var store = Ext.create('Ext.data.Store', {
fields: fields,
autoDestroy: false,
pageSize : 200,
buffered : true,
purgePageCount: 0,
remoteSort: true,
proxy: {
type: 'direct',
api : { read : AmdaAction.readTTCacheIntervals },
// remplir automatiquement tt, sharedtt , catalog, shared catalog
extraParams : {'typeTT' : 'catalog'},
reader:
{
type: 'json',
root: 'intervals',
totalProperty : 'totalCount'
}
},
listeners: {
scope : me,
load: function(store,records) {
// myDesktopApp.EventManager.fireEvent('refresh');
me.TTGrid.getView().refresh();
me.TTGrid.getSelectionModel().refresh();
me.updateCount();
//Statistical plugin
// this.fireEvent("refresh");
}
}
});
me.TTGrid.reconfigure(store, columns);
}
me.TTGrid.getSelectionModel().deselectAll();
//
// // clear filters
// me.TTGrid.getStore().clearFilter(true);
//
// //clear sort
// me.TTGrid.getStore().sorters.clear();
// //me.TTGrid.getStore().sorters = new Ext.util.MixedCollection();
//set cache token to the Catalog object
me.object.set('cacheToken', result.token);
me.setParamInfo(result.parameters);
me.TTGrid.getStore().load();
me.status = result.status;
},
/**
* load object catalog into this view
*/
loadObject : function(){
// load object into form
this.formPanel.getForm().loadRecord(this.object);
this.status = null;
if (this.object.get('fromPlugin')){
if (this.object.get('objFormat') && this.object.get('objFormat') != ''){
//From uploaded file
AmdaAction.initTTCacheFromUploadedFile(this.object.get('objName'), this.object.get('objFormat'), this.isCatalog, this.onAfterInit, this);
}
else {
//From tmp object (ie Statistics result)
AmdaAction.initTTCacheFromTmpObject(this.object.get('folderId'), this.object.get('objName'), this.isCatalog, this.onAfterInit, this);
}
}
else {
var typeTT = myDesktopApp.getLoadedModule(myDesktopApp.dynamicModules.catalog.id).linkedNode.data.nodeType;
if (this.object.get('id') == '') {
//TODO ?
}
else {
//From existing TT file
AmdaAction.initTTCacheFromTT(this.object.get('id'), typeTT, this.onAfterInit, this);
}
}
},
checkIntervalsStatusForSave : function(onStatusOk) {
onStatusOk();
},
/*
* save method called by Save button
*/
saveProcess : function(toRename)
{
var module = myDesktopApp.getLoadedModule(myDesktopApp.dynamicModules.catalog.id);
// store / columns are the same - not needed to reconfigure grid
this.toReconfigure = false;
// if the name has been modified this is a creation
if (this.fclose()) {
if (this.object.isModified('name') || this.object.get('fromPlugin')) {
// if object already has an id : it's a 'rename' of an existing
if (this.object.get('id')){
// the context Node is the parent node of current edited one
var contextNode = module.linkedNode.parentNode;
// link a new node to the TimeTableModule
module.createLinkedNode();
// set the contextNode
module.linkedNode.set('contextNode',contextNode);
// create a new object linked
module.createObject(this.object.getJsonValues());
var obj = module.linkedNode.get('object');
// synchronisation of objects
this.object = obj;
if (toRename) module.linkedNode.toRename = true;
}
module.linkedNode.create(/*{callback : function() {module.linkedNode.update();}, scope : this}*/);
} else {
//update
module.linkedNode.update();
}
}
},
/**
* overwrite metod called by Save button
*/
overwriteProcess : function(btn) {
if (btn == 'cancel') return;
this.fieldName.clearInvalid();
this.saveProcess(true);
},
/**
* 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;
},
init : function (config)
{
this.object = config.object;
this.fieldName = new Ext.form.field.Text({
fieldLabel: 'Name',
allowBlank : false,
stripCharsRe: /(^\s+|\s+$)/g,
emptyText: 'Please no spaces!',
name: 'name',
validateOnChange: false,
validateOnBlur: false,
validFlag: false,
validator : function() {
return this.validFlag;
}
});
var cellEditing = Ext.create('Ext.grid.plugin.CellEditing',{
// clicksToEdit: 2,
onEditComplete : function(ed, value, startValue) {
var me = this,
activeColumn = me.getActiveColumn(),
context = me.context,
record;
if (activeColumn) {
record = context.record;
me.setActiveEditor(null);
me.setActiveColumn(null);
me.setActiveRecord(null);
context.value = value;
if (!me.validateEdit()) {
me.editing = false;
return;
}
// Only update the record if the new value is different than the
// startValue. When the view refreshes its el will gain focus
if (!record.isEqual(value, startValue)) {
var obj = {};
obj['cacheId'] = record.get('cacheId');
obj['isCatalog'] = true;
obj[activeColumn.dataIndex] = value;
//Interval is modified on the server side
me.editing = true;
AmdaAction.modifyTTCacheInterval(obj, function (result, e) {
var module = myDesktopApp.getLoadedModule(myDesktopApp.dynamicModules.catalog.id);
if (module)
module.getUiContent().status = result.status;
context.grid.getSelectionModel().deselectAll();
context.store.reload({
callback : function(records, options, success) {
context.view.bufferedRenderer.scrollTo(context.rowIdx, true, function() {
me.fireEvent('edit', me, context);
me.editing = false;
}, me);
}
});
}, this);
}
else
me.editing = false;
}
}
});
this.TTGrid = Ext.create('Ext.grid.Panel', {
height: 530,
columns: [ ],
frame: true,
columnLines: true,
// selType: 'cellmodel',
plugins: [ cellEditing, { ptype : 'bufferedrenderer'} ],
dockedItems: [{
xtype: 'toolbar',
items: [{
iconCls: 'icon-add',
scope: this,
handler: function(){
cellEditing.cancelEdit();
var store = this.TTGrid.getStore();
var selection = this.TTGrid.getView().getSelectionModel().getSelection()[0];
var row = 0;
if (selection)
row = store.indexOf(selection) + 1;
this.TTGrid.getSelectionModel().deselectAll();
var me = this;
AmdaAction.addTTCacheInterval({'index' : row, 'isCatalog' : true}, function (result, e) {
this.status = result.status;
this.TTGrid.getStore().reload({
callback : function(records, options, success) {
me.TTGrid.getView().bufferedRenderer.scrollTo(row, false, function() {
me.TTGrid.getView().select(row);
cellEditing.startEditByPosition({row: row, column: 1});
}, me);
}
});
}, this);
}
},{
iconCls: 'icon-delete',
disabled: true,
itemId: 'delete',
scope: this,
handler: function(){
var selection = this.TTGrid.getView().getSelectionModel().getSelection()[0];
if (selection)
{
var rowId = selection.get('cacheId');
this.TTGrid.getSelectionModel().deselectAll();
AmdaAction.removeTTCacheIntervalFromId(rowId, this.isCatalog, function (result, e) {
this.status = result.status;
this.TTGrid.getStore().reload();
}, this);
}
}
}]
}]
});
this.formPanel = Ext.create('Ext.form.Panel', {
region : 'center',
layout: 'hbox',
bodyStyle: {background : '#dfe8f6'},
defaults: { border : false, align: 'stretch', bodyStyle: {background : '#dfe8f6'}, padding: '3'},
fieldDefaults: { labelWidth: 80, labelAlign : 'top' },
items: [{
xtype: 'form',
flex: 1,
buttonAlign: 'left',
// title : 'Information',
layout: {type: 'vbox', pack: 'start', align: 'stretch'},
items : [
this.fieldName,
{
xtype: 'fieldcontainer',
layout: 'hbox',
items: [{
xtype:'datefield', fieldLabel:'Creation date',
name: 'created', disabled: true,
hideTrigger: true, format: 'Y/m/d H:i:s'
},
{ xtype: 'splitter' },
{ xtype:'textfield', fieldLabel: 'Intervals', name: 'nbIntervals', disabled: true }
]
},
{
xtype: 'textarea',
name: 'description',
fieldLabel: 'Description',
height: 200
},
{
xtype: 'component',
height: 180
}],
dockedItems:[{
xtype: 'toolbar',
dock: 'bottom',
ui: 'footer',
items: [{
type: 'button',
text: 'Create New Catalog',
scope : this,
handler: function ()
{
var module = myDesktopApp.getLoadedModule(myDesktopApp.dynamicModules.catalog.id);
if (!module) return;
var obj = module.linkedNode.get('object');
if (obj && obj.get('id') == '' && !obj.get('fromPlugin')) {
var me = this;
Ext.Msg.prompt('Define Parameters', 'Please enter parameters number:', function(btn, text){
if (btn == 'ok'){
AmdaAction.initTTCache(me.isCatalog, text, me.onAfterInit, me);
}
}, this);
}
}
}]
},
{
xtype: 'toolbar',
dock: 'bottom',
ui: 'footer',
items: [
{
type: 'button',
text: 'Save',
scope : this,
handler: function ()
{
if (this.updateObject())
{
var basicForm = this.formPanel.getForm();
// if there's at least one record in the store of TTGrid
if (this.TTGrid.getStore().getTotalCount() > 0)
{
// update TimeTable object which the content of form
basicForm.updateRecord(this.object);
var me = this;
this.checkIntervalsStatusForSave(function () {
//Name validation
var module = myDesktopApp.getLoadedModule(myDesktopApp.dynamicModules.catalog.id);
if (!module) return;
module.linkedNode.isValidName(me.fieldName.getValue(), function (res)
{
if (!res) {
me.fieldName.validFlag = 'Error during object validation';
myDesktopApp.errorMsg(me.fieldName.validFlag);
me.fieldName.validate();
return;
}
if (!res.valid) {
if (res.error) {
if (res.error.search('subtree') != -1) {
Ext.MessageBox.show({title:'Warning',
msg: res.error+'
Do you want to overwrite it?',
width: 300,
buttons: Ext.MessageBox.OKCANCEL,
fn : me.overwriteProcess,
icon: Ext.MessageBox.WARNING,
scope : me
});
me.fieldName.validFlag = true;
}
else
me.fieldName.validFlag = res.error;
}
else {
me.fieldName.validFlag = 'Invalid object name';
myDesktopApp.errorMsg(me.fieldName.validFlag);
}
me.fieldName.validate();
return;
}
me.fieldName.validFlag = true;
me.fieldName.validate();
me.saveProcess(false);
});
});
}
else {
Ext.Msg.alert('No intervals', 'Your time table is invalid,
you must have at least one interval');
}
}
}
},{
type: 'button',
text: 'Reset',
scope : this,
disabled: true,
handler: function() {
// var module = myDesktopApp.getLoadedModule(myDesktopApp.dynamicModules.catalog.id);
// module.createLinkedNode();
// module.createObject();
// this.setObject(module.getLinkedNode().get('object'), true);
}
},
{
type: 'button',
text: 'Share',
disabled: true
},
{
type: 'button',
text: 'Visualize',
scope: this,
handler: function() {
var me = this;
myDesktopApp.getLoadedModule(myDesktopApp.dynamicModules.visu.id, true, function (module) {
//temporary linked node - as Visu module is 'pseudo' interactive - no 'save', no 'execute'
var temporaryNode = Ext.create('amdaModel.CatalogNode', { leaf : true });
if (temporaryNode) temporaryNode.set('object',me.object);
module.setLinkedNode(temporaryNode);
module.createWindow();
});
}
}]
}]
},
{
xtype: 'form',
bodyStyle: {background : '#dfe8f6'},
//padding: '3',
flex: 2,
items : [ this.TTGrid ]
}]
});
this.TTGrid.getSelectionModel().on('selectionchange', function(selModel,selections) {
this.TTGrid.down('#delete').setDisabled(selections.length === 0);
}, this);
var myConf = {
layout: 'border',
items: [
this.formPanel,
{
xtype: 'panel',
region: 'south',
title: 'Information',
collapsible: true,
height: 100,
autoHide: false,
bodyStyle: 'padding:5px',
iconCls: 'icon-information',
loader:
{
autoLoad: true,
url: helpDir+'catalogHOWTO'
}
}
]
};
Ext.apply (this, Ext.apply(arguments, myConf));
}
});