// Thought Junction Javascript Startup Engine.
// TJ Admin Record management components

/* Management for Table_ID */

// Record Viewing!!!
	TJ.Admin.TablePreviewGridPanel = Ext.extend(Ext.grid.GridPanel,{
		autoExpandColumn: 1,
		autoScroll: true,
		columns: [
			   {header: "Field", dataIndex: 'field'},
			   {header: "Value", dataIndex: 'value'}
		  ],
		  stripeRows: true,

		initComponent:function() {
			this.store = new Ext.data.SimpleStore({
				fields: [
				   {name: 'field'},
				   {name: 'value'}
				]
			});

			this.tbar = [ { tooltip: 'Refresh',
							text:'Refresh',
						   iconCls: 'icon-refresh',
//				            handler: this.refresh,
		                    scope: this
			}];
			if(!this.tableinfo.readonly)
				this.tbar.push(
				{
					text:'Delete',
					tooltip:'Delete this ' + this.tableinfo.lang.label ,
					iconCls:'icon_table_delete',
					scope: this,
					handler : function () {
						if(this.record && this.record._id){ // check if record exists
							var msg='<TABLE>';
							msg=msg +'<TR><TD>' + this.record['_id'] + '</TD><TD>' + this.record[this.tableinfo.summary]+'</TD></TR>';
							msg=msg+'</TABLE>';
//							console.log(msg);


							Ext.Msg.show({
							   title:'Please confirm',
							   width: 300,
							   msg: 'Are you sure you want to delete the following record?<BR> ' + msg,
							   buttons: Ext.Msg.YESNO,
							   fn: function(btn){ if(btn=='yes') {
										Ext.Ajax.request ({ url:	TJ.LANGUAGESS + this.tableinfo.baseurl + ':delete?ids=' + this.record['_id'], 
															id: this.record['_id'],
															table: this.tableinfo.table,
											callback: function(options, success, response)  {
												var res=TJ.Admin.ProcessJSONResponse(options,success,response);
												TJ.Admin.TableManager.tableDataChange(options.table,'delete',options.id);
											}
										});
									}
							   },
							   scope: this,
							   animEl: this,
							   icon: Ext.MessageBox.QUESTION
							});



						}
					}
				});


			this.initialTitle = ('Preview ' + this.tableinfo.lang.label);
			this.title = this.initialTitle;
			
			for(var i=0;i<this.tableinfo.columns.length;i++){
				if(this.tableinfo.columns[i].evalrenderer) {
					this.tableinfo.columns[i].renderer = eval(this.tableinfo.columns[i].evalrenderer);
				}

			}


			TJ.Admin.TablePreviewGridPanel.superclass.initComponent.call(this);

			if(this.recordid)
				this.setRecordByID(this.recordid);
//				console.log('set this record',this.recordid);
//			this.setRecordByObject(record.data);

			this.refreshRequired=false;
			TJ.Admin.TableManager.on('tabledatachange',this.tableDataChange,this);


		},
		tableDataChange: function(table,operation,recordid){
			if(table == this.tableinfo.table) {
				if(operation=='delete'){
					var newdata=[];
					newdata.push(['Record' ,'Deleted']);
					this.store.loadData(newdata);
					this.setTitle(this.initialTitle);
					this.record=null;
				} else if (operation=='edit'){
					this.doRefresh(recordid);
				}
			}
		},
	
		setRecord : function(record){
			this.setRecordByObject(record.data);
		},
		setRecordByObject: function(record) {
			var newdata=[];
			if(record) {
				for(var i=0;i<this.tableinfo.columns.length;i++){

					if(this.tableinfo.columns[i].renderer3){
							newdata.push([ this.tableinfo.columns[i].header ,
									this.tableinfo.columns[i].renderer(record[this.tableinfo.columns[i].dataIndex])
						]);						
					}
					else
						newdata.push([ this.tableinfo.columns[i].header ,record[this.tableinfo.columns[i].dataIndex]]);

				}
//				for(var key in record)
//					newdata.push([key,record[key]]);
				this.store.loadData(newdata);
				this.setTitle(this.initialTitle);
				this.record = record;
			
			} else {
				newdata.push(['Record' ,'Not Found']);
				this.store.loadData(newdata);
				this.setTitle(this.initialTitle);
				this.record=null;
			}
		},


		refresh: function(){
			if (this.record)
				this.setRecordByID(this.record._id);
		},
		setRecordByID: function(recordid){
			if(recordid)
				this.recordid=recordid;
			Ext.Ajax.request ({ url:  TJ.LANGUAGESS + this.tableinfo.baseurl + '-' + recordid + ':getrecord',
								params: {id: recordid},
										callback: function (options,success, response) {
											var res=TJ.Admin.ProcessJSONResponse(options,success, response);
											this.setRecordByObject(res.record);

										},
										scope:this
										});
			
		},
		doRefresh: function(recordid) {
			if(recordid == this.record._id) {
				this.refreshRequired=true;
				this.setTitle(this.initialTitle + '*');
			}
		}

	});
	Ext.reg('tjadminrecordview',TJ.Admin.TablePreviewGridPanel);


TJ.Admin.RecordEditForm = Ext.extend(TJ.Admin.StatusPanelForm,{
	initComponent: function (){
		this.title='Edit ' + this.tableinfo.lang.label;
		this.formconfig.url=this.rooturl + ':doedit';
		TJ.Admin.RecordEditForm.superclass.initComponent.call(this);
	}
});

Ext.reg('tjadminrecordedit',TJ.Admin.RecordEditForm);

TJ.Admin.RecordCopyForm = Ext.extend(TJ.Admin.StatusPanelForm,{
//	disabled: true,
	initComponent: function (){
		this.title='Copy ' + this.tableinfo.lang.label;
		this.formconfig.url=this.rooturl + ':docopy';
		TJ.Admin.RecordEditForm.superclass.initComponent.call(this);
	}
});

Ext.reg('tjadminrecordcopy',TJ.Admin.RecordCopyForm);

	TJ.Admin.RecordHistoryPanel = Ext.extend(Ext.grid.GridPanel, {
        stripeRows: true,
		initComponent: function(){
			this.initialTitle = this.title='Viewing history of this ' + this.tableinfo.lang.label;
	        this.columns = [
					{header: "Timestamp", width: 125, sortable: true, renderer: Ext.util.Format.dateRenderer('Y/m/d H:i:s'), dataIndex: 'timestamp'},
					{header: "Action", width: 100, sortable: true, dataIndex: 'action', renderer: this.renderAction},
					{header: "Username (ID)", width: 150, sortable: true, dataIndex: 'username', renderer: this.renderUsername},
					{header: "Description", dataIndex: 'desc'}
				];


				this.store = new Ext.data.Store( {
					remoteSort: true,
					proxy: new Ext.data.HttpProxy({
						url:  TJ.LANGUAGESS + this.tableinfo.baseurl + '-' + this.recordid + ':gethistory' }),
					reader: new Ext.data.JsonReader({
						root: 'rows',
						totalProperty: 'numrows'
						},
						[	{name:'timestamp', type:'date', dateFormat:"Y-m-d H:i:s"},
							{name:'action'},
							{name:'username'},
							{name:'desc'},
							{name:'userid'}
							])
					});
				this.store.on('load',function(){this.setTitle(this.initialTitle);},this);
				this.bbar =  new Ext.PagingToolbar({
					pageSize: 20,
					store: this.store,
					displayInfo: true,
					displayMsg: 'Displaying history  {0} - {1} of {2}',
					emptyMsg: 'No history to display'
				});

				this.store.load({params: {start: 0, limit: 20}});
				TJ.Admin.RecordHistoryPanel.superclass.initComponent.call(this);
				TJ.Admin.TableManager.on('tabledatachange',this.tableDataChange,this);
			},
			tableDataChange: function(table,operation,recordid){
				if( (table==this.tableinfo.table) && (recordid==this.recordid)) {
					this.setTitle(this.initialTitle +'*');
				}
			},
			renderUsername:function(value,p,record){
				return String.format('{0} ({1})',record.data.username, record.data.userid);
			},
			renderAction:function(value,p,record){
				return value ;
			}
	});

Ext.reg('tjadminrecordhistory',TJ.Admin.RecordHistoryPanel);




/* Management for Table_Type */


/* Secure Handling */


TJ.Admin.RecordSecurePanel = Ext.extend(Ext.TabPanel,{
	activeTab: 0,
	defaults : {
					autoScroll: true,
					layout: 'fit',
					loaded: false},

	initComponent: function(){
		this.title='Secure access for this ' + this.tableinfo.lang.plural;
		this.items = [ {title: 'Users',
						func: 'users'
						},
						{title: 'Usergroups',
						 func: 'groups'
						 }
						 ];
		this.on('tabchange',this.tabChange);
		TJ.Admin.RecordSecurePanel.superclass.initComponent.call(this);
	},
	tabChange: function(mainpanel,tab) {
		if(tab.func) {
			if(! tab.loaded) {
				var panel;
				if(tab.func=='users') {
					TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + 'admin/apps/content-cl_user_account_table:gettableinfo2', 
												callback: function(val){ 
					panel = new TJ.Admin.TableRelatedGridPanel({title: 'Users with access to this content',
																tableinfo: val, 
																relation: {table: this.tableinfo['class'], 
																id: this.recordid}});
							tab.add(panel);
							tab.doLayout();
							tab.loaded=true;						
												},
												scope: this});


				} else
				if(tab.func=='groups') {
					TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + 'admin/apps/content-cl_user_group_table:gettableinfo2', 
												callback: function(val){ 

					panel = new TJ.Admin.TableRelatedGridPanel({title: 'Usergroups with access to this content',
																		tableinfo: val, relation: {table: this.tableinfo['class'], id: this.recordid}});
					tab.add(panel);
					tab.doLayout();
					tab.loaded=true;
												},
												scope: this});

				} else
				console.log(tab.func);
			}
		}
	}
});

Ext.reg('tjadminrecordsecure',TJ.Admin.RecordSecurePanel);


// Related
TJ.Admin.RecordRelatedGridPanel = Ext.extend(TJ.Admin.TableAddRemoveGridPanel,{
	initComponent: function(){
		this.baseParams = this.relation;
//		this.tableinfo = TJ.Admin.TableInfo[this.table];
//		Done in the card config.
		TJ.Admin.TableRelatedGridPanel.superclass.initComponent.call(this);
	},
	addRecord: function(record){
		Ext.Ajax.request ({ url:  TJ.LANGUAGESS + this.tableinfo.baseurl + ':relatedadd',
							params: {reltab: this.relation.table, relid: this.relation.id, relname: this.relation.relname, id: record._id},
							callback: function (options,success, response) {
								var res=TJ.Admin.ProcessJSONResponse(options,success, response);
								if(res.success) {
									this.store.reload();
								}},
							scope: this	});

	},
	removeRecords: function(records,ids){
		Ext.Ajax.request ({ url:  TJ.LANGUAGESS +  this.tableinfo.baseurl + ':relatedrem',
							params: {reltab: this.relation.table, relid: this.relation.id, relname: this.relation.relname, ids:  ids.join(',')},
							callback: function (options,success, response) {
								var res=TJ.Admin.ProcessJSONResponse(options,success, response);
								if(res.success) {
									for(var i=0; i < records.length; i++) {
										this.store.remove(records[i]);
										ids[i]=records[i].data['_id'];
									}
								}},
							scope: this	});
	}

});


Ext.reg('tjadminrecordrelated',TJ.Admin.RecordRelatedGridPanel);