Ext.namespace('com.evoca.twitter');

var twitterAccountID;
var userID;
var record;
var cachedTwitterStore;
var twitterStore;
com.evoca.twitter.renderTwitterGrid = function(root, divID, userIDParam, limit, gridTitle, gridWidth) {
	logger.startLogGroup('com.evoca.twitter.renderTwitterGrid');
	
	Ext.state.Manager.setProvider(new Ext.state.CookieProvider())

	if(gridWidth == null || gridWidth <= 0)
		gridWidth = 780;

	
	userID = userIDParam;
	this.root = root;
	this.limit = limit;

	// Initialize quicktips
	Ext.QuickTips.init();
			
	Ext.apply(Ext.QuickTips.getQuickTip(), {
		maxWidth: 200,
		minWidth: 100,
		showDelay: 50,
		trackMouse:  true
	});
			
	userID = userIDParam;
	
	if(!Ext.isGecko) {
		var pushSettingData = [
			['all', 'All', ''],
			['all', 'All', ''],
			['publicOnly', 'Public only', ''],
			['privateOnly', 'Private only', ''],
			['disabled', 'Disabled', '']
		];
	}
	else {
		var pushSettingData = [
			['all', 'All', ''],
			['publicOnly', 'Public only', ''],
			['privateOnly', 'Private only', ''],
			['disabled', 'Disabled', '']
		];
	}
	
	var enableDisableData = [
		['true', 'Enabled'],
		['false', 'Disabled']
	];

	var nameValueReader = new Ext.data.ArrayReader({}, [
		{name: 'value'},
		{name: 'name'},
		{name: 'css'} // The css to apply to the item
	]);

	var twitterUtils = new com.evoca.twitter.TwitterUtils();

	this.twitterStore = twitterUtils.getTwitterStore(root, userID, true, limit); 
	twitterStore = this.twitterStore;
	cachedTwitterStore = this.twitterStore;
	
	this.enableDisableStore = new Ext.data.Store({
		reader: nameValueReader,
		data: enableDisableData
	});
	
	var pushSettingStore = new Ext.data.Store({
		id: 0,
		reader: nameValueReader,
		data: pushSettingData
	});
	
	var deleteColumn = new com.evoca.twitter.deleteColumn({
		id: 'delete',
		width: 40,
		header: 'Delete',
		sortable: false
	});
	
	var imageColumn = new com.evoca.twitter.imageColumn({
		id: 'imageColumn',
		width: 40,
		scope: this,
		sortable: false,
		header: 'Image',
		dataIndex: 'twitterActivePage',
		css: (Ext.isChrome || Ext.isSafari) ? 'width: 40px !important;' : ''
	});

	var viewDetailsColumn = new com.evoca.twitter.viewDetailsColumn({
		id: 'viewDetails',
		width: 35,
		scope: this,
		header: 'Edit',
		sortable: false
	});
	
	var pushSettingEditorPhone = new Ext.form.ComboBox({
		id: 'pushSettingEditorPhone',
		readOnly: true,
		//listWidth: 50,
		store: pushSettingStore,
		valueField: 'value',
		displayField: 'name',
		mode: 'local',
		triggerAction: 'all',
		editable: false,
		scope: this
	});
	
	pushSettingEditorPhone.on('focus', function(){
		var pushToTwitterOnNewPublicPhoneRecording = record.get('pushToTwitterOnNewPublicPhoneRecording');
		var pushToTwitterOnNewPrivatePhoneRecording = record.get('pushToTwitterOnNewPrivatePhoneRecording');
		
		if(pushToTwitterOnNewPublicPhoneRecording && pushToTwitterOnNewPrivatePhoneRecording) {
			pushSettingEditorPhone.setValue('all');
		}
		else if(pushToTwitterOnNewPublicPhoneRecording) {
			pushSettingEditorPhone.setValue('publicOnly');
		}
		else if(pushToTwitterOnNewPrivatePhoneRecording) {
			pushSettingEditorPhone.setValue('privateOnly');
		}
		else {
			pushSettingEditorPhone.setValue('disabled');
		}
	});
	
	var pushSettingEditorSkype = new Ext.form.ComboBox({
		id: 'pushSettingEditorSkype',
		readOnly: true,
		//listWidth: 50,
		store: pushSettingStore,
		valueField: 'value',
		displayField: 'name',
		mode: 'local',
		triggerAction: 'all',
		editable: false,
		scope: this
	});
	
	pushSettingEditorSkype.on('focus', function() {
		var pushToTwitterOnNewPublicSkypeRecording = record.get('pushToTwitterOnNewPublicSkypeRecording');
		var pushToTwitterOnNewPrivateSkypeRecording = record.get('pushToTwitterOnNewPrivateSkypeRecording');
		
		if(pushToTwitterOnNewPublicSkypeRecording && pushToTwitterOnNewPrivateSkypeRecording) {
			pushSettingEditorSkype.setValue('all');
		}
		else if(pushToTwitterOnNewPublicSkypeRecording) {
			pushSettingEditorSkype.setValue('publicOnly');
		}
		else if(pushToTwitterOnNewPrivateSkypeRecording) {
			pushSettingEditorSkype.setValue('privateOnly');
		}
		else {
			pushSettingEditorSkype.setValue('disabled');
		}
	});
	
	var notesEditor =   new Ext.form.TextArea({
		allowBlank: true,
		id: 'notesEditor',
		blankText: 'Enter notes about the Twitter account here.',
		autoHeight: true
	});
	
	var nameEditor = new Ext.form.TextField({
		allowBlank: false,
		id: 'nameEditorID',
		blankText: 'Please enter a name.',
		readOnly: true,
		selectOnFocus: true
	});
	
	var prefixEditorPhone = new Ext.form.TextField({
		allowBlank: true,
		id: 'pefixEditorPhoneID',
		blankText: 'Please enter a prefix.',
		readOnly: false,
		selectOnFocus: false
	});
	
	var prefixEditorSkype = new Ext.form.TextField({
		allowBlank: true,
		id: 'pefixEditorSkypeID',
		blankText: 'Please enter a prefix.',
		readOnly: false,
		selectOnFocus: false
	});
	

	
	var secWidth = 50;
	
	if(Ext.isIE)
		secWidth = secWidth + 3;
	
	var cssWidth = '  ';
	if(Ext.isChrome || Ext.isSafari) {
		cssWidth = ' width: ' + (secWidth + 1) + 'px !important; ';
	}
	
	var columnModel = new Ext.grid.ColumnModel([
		viewDetailsColumn,
		{id:'twitterUserName',header: 'Username', width: 150, sortable: true, dataIndex: 'twitterUserName', editor: nameEditor},
		{id:'pushToTwitterSettingForPhoneRecordings',header: 'Auto-post new phone recordings', width: 170, sortable: true, dataIndex: 'pushToTwitterSettingForPhoneRecordings', editor: pushSettingEditorPhone, renderer: function(v, params, record) {
			logger.startLogGroup(this.id);

			var pushToTwitterOnNewPublicPhoneRecording = record.get('pushToTwitterOnNewPublicPhoneRecording');
			var pushToTwitterOnNewPrivatePhoneRecording = record.get('pushToTwitterOnNewPrivatePhoneRecording');

			var text = '';

			if(pushToTwitterOnNewPublicPhoneRecording && pushToTwitterOnNewPrivatePhoneRecording) {
				logger.debug('push to twitter on all phone recording');
				text = 'All';
			}
			else if(pushToTwitterOnNewPublicPhoneRecording) {
				logger.debug('push to twitter on public phone recordings only');
				text = 'Public only';
			}
			else if(pushToTwitterOnNewPrivatePhoneRecording) {
				logger.debug('push to twitter on private phone recordings only');
				text = 'Private only';
			}
			else {
				logger.debug('never push to twitter on all phone recordings');
				text = 'Disabled';
			}
			
			logger.endLogGroup(this.id);
			return '<center>' + text + '</center>';
		}},
		{id:'prefixForNewPhoneRecordings',header: 'Auto-post phone prefix', width: 150, sortable: true, dataIndex: 'prefixForNewPhoneRecordings', editor: prefixEditorPhone, renderer: function(v, params, record){
			params.attr += 'ext:qtip=\"' + prefixPhoneNotes + '\'.\"';
			
			return v;
		}},
		//{id:'prefixForNewPhoneRecordings',header: 'Auto-post phone prefix', width: 123, sortable: true, dataIndex: 'prefixForNewPhoneRecordings', editor: nameEditor},
		{id:'pushToTwitterSettingForSkypeRecordings',header: 'Auto-post new Skype recordings', width: 170, sortable: true, dataIndex: 'pushToTwitterSettingForSkypeRecordings', editor: pushSettingEditorSkype, renderer: function(v, params, record) {
			logger.startLogGroup(this.id);
			
			var pushToTwitterOnNewPublicSkypeRecording = record.get('pushToTwitterOnNewPublicSkypeRecording');
			var pushToTwitterOnNewPrivateSkypeRecording = record.get('pushToTwitterOnNewPrivateSkypeRecording');
			
			logger.debug('pushToTwitterOnNewPublicSkypeRecording: ' + pushToTwitterOnNewPublicSkypeRecording);
			logger.debug('pushToTwitterOnNewPrivateSkypeRecording: ' + pushToTwitterOnNewPrivateSkypeRecording);
			
			var text = '';
			
			logger.debug('pushToTwitterOnNewPublicSkypeRecording && pushToTwitterOnNewPrivateSkypeRecording: ' + (pushToTwitterOnNewPublicSkypeRecording && pushToTwitterOnNewPrivateSkypeRecording));
			
			if(pushToTwitterOnNewPublicSkypeRecording && pushToTwitterOnNewPrivateSkypeRecording) {
				logger.debug('push to twitter on all phone recording');
				text = 'All';
			}
			else if(pushToTwitterOnNewPublicSkypeRecording) {
				logger.debug('push to twitter on public phone recordings only');
				text = 'Public only';
			}
			else if(pushToTwitterOnNewPrivateSkypeRecording) {
				logger.debug('push to twitter on private phone recordings only');
				text = 'Private only';
			}
			else {
				logger.debug('never push to twitter on all phone recordings');
				text = 'Disabled';
			}
			
			logger.endLogGroup(this.id);
			return '<center>' + text + '<center>';
		}},
		{id:'prefixForNewSkypeRecordings',header: 'Auto-post Skype prefix', width: 150, sortable: true, dataIndex: 'prefixForNewSkypeRecordings', editor: prefixEditorSkype, renderer: function(v, params, record){
			params.attr += 'ext:qtip=\"' + prefixSkypeNotes + '\'.\"';
			
			return v;
		}},
		//{id:'prefixForNewSkypeRecordings',header: 'Auto-post Skype prefix', width: 123, sortable: true, dataIndex: 'prefixForNewSkypeRecordings', editor: nameEditor},
		{id:'notes',header: 'Comments', sortable: true, dataIndex: 'notes', editor: notesEditor, renderer: function(v, params, record){
			params.attr += 'ext:qtip=\"' + v + '\"';
			return v;
		}},
		deleteColumn
	]);
	
	var title = 'My Twitter accounts';
	
	if(gridTitle != null && gridTitle != '') {
		title = gridTitle;
	}
	
	grid = new Ext.grid.EditorGridPanel({
		ds: this.twitterStore,
		id: 'mainTwitterTable',
		cm: columnModel,
		stripeRows: true,
		frame: true,
		autoExpandColumn: 'notes',
		autoHeight: true,
		width: gridWidth,
		title: title,
		stateful: false, // TODO: (TF) Turn statefulness back on
		//stateful: true,
		stateId: 'twittergrid',
		scope: this,
		clicksToEdit: 1
	});
	
	grid.render(divID);
	
	function cellClick(grid, rowIndex, columnIndex, e, parent) {
		var columnObj = grid.getColumnModel().config[columnIndex];
		
		record = grid.getStore().getAt(rowIndex);
		
		twitterAccountID = record.get('twitterAccountID');
		
		if(columnObj.handleClick)
			columnObj.handleClick(grid, rowIndex, columnIndex, e, this);
	}
	grid.on('cellclick', cellClick);
	
	// This listener will auto-update whenever all cell is changed
	grid.on('validateedit', function(e) {
		twitterUtils.updateTwitterAccount(root, twitterAccountID, e.field, e.value);
	});
	
	logger.endLogGroup('com.evoca.twitter.renderTwitterGrid');
};

com.evoca.twitter.deleteColumn = function(config){
	Ext.apply(this, config);
	if(!this.id){
		this.id = Ext.id();
	}
};
	
com.evoca.twitter.deleteColumn.prototype ={
	renderer : function(v, p, record){
		p.css += ' delete-column';
		p.attr += 'ext:qtip=\"Delete \'' + record.get('twitterUserName') + '\'.\"';
		return '&#160;';
	},
	
	handleClick : function(grid, rowIndex, columnIndex, e) {
		var record = grid.getStore().getAt(rowIndex);
		
		Ext.Msg.show({
			title: 'Delete',
			buttonAlign: 'center',
			buttons: Ext.Msg.YESNO,
			msg: 'Are you sure you want to delete the Twitter account: ' + record.get('twitterUserName') + '?',
			fn: function(btn, text) {
				if(btn == 'yes') {
					Ext.Ajax.request({
						url: root + 'Request?action=deleteTwitterAccount&taid=' + record.get('twitterAccountID'),
						success: function(response) {
							grid.store.remove(record);
						}, 
						failure: function(){
							Ext.Msg.show({
								title: 'Failure',
								buttonAlign: 'center',
								buttons: Ext.Msg.OK,
								msg: 'The Twitter account could not be deleted. Please try again later.',
								fn: function() {
									this.hide();
									window.location.reload();
								},
								scope: this
							});
						},
						scope: this
					});
				}
			},
			scope: this
		});
	}
};

com.evoca.twitter.viewDetailsColumn = function(config){
	Ext.apply(this, config);
	if(!this.id){
		this.id = Ext.id();
	}
};
	
com.evoca.twitter.viewDetailsColumn.prototype ={
	renderer : function(v, p, record){
		p.css += ' configure-column';
		p.attr += 'ext:qtip=\"View \'' + record.get('twitterUserName') + '\'.\"';
		return '&#160;';
	},
	
	// TODO: (TF) update this function
	handleClick : function(grid, rowIndex, columnIndex, e) {
		var record = grid.getStore().getAt(rowIndex);

		var taid = record.get('twitterUserID');
		var username = record.get('twitterUserName');
		
		var url = root + 'myaccount/twitter-preferences.jsp?taid=' + taid + '&twitterUserName=' + username;

		window.location =  url;
	}
};

com.evoca.twitter.imageColumn = function(config){
	Ext.apply(this, config);
	if(!this.id){
		this.id = Ext.id();
	}
};
	
com.evoca.twitter.imageColumn.prototype ={
		// TODO: (TF) update this function
	renderer : function(v, p, record){
		if(record.get('hasPhoto') == 1) {
			p.css += ' image-column';
			var qtip = '<img height=\'140\' src=\'' + root + 'ImageRetriever?oid=A' + record.get('twitterAccountID') + '\' />';
			p.attr = 'ext:qtip="' + qtip + '"';
		}
		else {
			p.css += ' image-column-disabled';
		}
		
		return '&#160;';
	},
	
	// TODO: (TF) update this function
	handleClick : function(grid, rowIndex, columnIndex, e) {
		var record = grid.getStore().getAt(rowIndex);
			
		var window = new com.evoca.twitter.ImageManagementWindow(record);
		window.show();
	}
};

com.evoca.twitter.TwitterUtils = function() {
	/**
	 * Returns an album list object based off xml string
	 */
	this.createTwitterRecord = function() {
		var record = Ext.data.Record.create([
			{name: 'twitterAccountID', type: 'int'}, // Our primary key for this record
			{name: 'userID', type: 'int'},
			{name: 'twitterUserID'},
			{name: 'twitterUserName'},
			{name: 'OAuth2Token'},
			{name: 'createDate'},
			{name: 'notes'},
			
			{name: 'pushToTwitterOnNewPublicPhoneRecording', type: 'bool'},
			{name: 'pushToTwitterOnNewPublicUploadedRecording', type: 'bool'},
			{name: 'pushToTwitterOnNewPublicSkypeRecording', type: 'bool'},
			{name: 'pushToTwitterOnNewPublicMicRecording', type: 'bool'},
			
			{name: 'pushToTwitterOnNewPrivatePhoneRecording', type: 'bool'},
			{name: 'pushToTwitterOnNewPrivateUploadedRecording', type: 'bool'},
			{name: 'pushToTwitterOnNewPrivateSkypeRecording', type: 'bool'},
			{name: 'pushToTwitterOnNewPrivateMicRecording', type: 'bool'},
			
			{name: 'prefixForNewPhoneRecordings'},
			{name: 'prefixForNewSkypeRecordings'},
			{name: 'prefixForNewMicRecordings'},
			{name: 'prefixForNewUploadRecordings'}
		]);
		
		return record;
	},
	
	this.getTwitterStore = function(root, userID, limit) {
		if(limit == null || limit < 0)
			limit = 999999;
		
		var extraParams = 'limit=' + limit;

		var url = root + 'Request?action=getTwitterAccounts&userID=' + userID + '&' + extraParams;
	
		
		var store = new Ext.data.Store({
			url: url,
			autoLoad: false,
			remoteSort: true,
			reader: new Ext.data.XmlReader({
				record : 'twitterAccount',
				totalRecords: 'totalTwitterAccounts'
			}, this.createTwitterRecord())
		});
		
		var state = Ext.state.Manager.getProvider();
		
		var start = Ext.state.Manager.getProvider().get('twitterActivePage');
		
		if(start == null || start <= 0)
			start = 0;
		
		var sort = null;//state.sort.field;
		var dir = null;//state.sort.direction;
		
		if(state && state.state && state.state.twittergrid && state.state.twittergrid.sort) {
			if(state.state.twittergrid.sort.field)
				sort = state.state.twittergrid.sort.field;
			
			if(state.state.twittergrid.sort.direction)
				dir = state.state.twittergrid.sort.direction;
		}
		
		if(sort == null || sort == '')
			sort = 'twitterUserName';
		
		if(dir == null || dir == '')
			dir = 'ASC';
		
		start = start * limit;
		
		store.load({params:{start:start, limit:limit, sort: sort, dir: dir}});
		
		return store;
	},
	
	this.updateTwitterAccount = function(root, twitterAccountID, field, value) {
		var logGroup = 'twitter.js this.updateTwitterAccount';
		logger.debug('foobar');
		logger.startLogGroup(logGroup);
		logger.debug(
			'\nroot: ' + root + 
			'\ntwitterAccountID: ' + twitterAccountID + 
			'\nfield: ' + field + 
			'\nvalue: ' + value);
		
		if(twitterAccountID && field) {
			var update = false;
			
			switch(field) {
				case "pushToTwitterSettingForPhoneRecordings":
					params = Ext.urlEncode({'pushToTwitterSettingForPhoneRecordings': value});
					update = true;
					
					switch(value) {
						case "all" :
							record.set('pushToTwitterOnNewPublicPhoneRecording', true);
							record.set('pushToTwitterOnNewPrivatePhoneRecording', true);
							break;
						case "publicOnly" :
							record.set('pushToTwitterOnNewPublicPhoneRecording', true);
							record.set('pushToTwitterOnNewPrivatePhoneRecording', false);
							break;
						case "privateOnly" :
							record.set('pushToTwitterOnNewPublicPhoneRecording', false);
							record.set('pushToTwitterOnNewPrivatePhoneRecording', true);
							break;
						default :
							record.set('pushToTwitterOnNewPublicPhoneRecording', false);
							record.set('pushToTwitterOnNewPrivatePhoneRecording', false);
							break;
					}
					
					break;
				case "pushToTwitterSettingForSkypeRecordings":
					params = Ext.urlEncode({'pushToTwitterSettingForSkypeRecordings': value});
					update = true;
					
					switch(value) {
						case "all" :
							record.set('pushToTwitterOnNewPublicSkypeRecording', true);
							record.set('pushToTwitterOnNewPrivateSkypeRecording', true);
							break;
						case "publicOnly" :
							record.set('pushToTwitterOnNewPublicSkypeRecording', true);
							record.set('pushToTwitterOnNewPrivateSkypeRecording', false);
							break;
						case "privateOnly" :
							record.set('pushToTwitterOnNewPublicSkypeRecording', false);
							record.set('pushToTwitterOnNewPrivateSkypeRecording', true);
							break;
						default :
							record.set('pushToTwitterOnNewPublicSkypeRecording', false);
							record.set('pushToTwitterOnNewPrivateSkypeRecording', false);
							break;
					}
					
					break;
				case "notes":
					params = Ext.urlEncode({'notes': value});
					update = true;
					record.set('notes', value);
					break;
				case "prefixForNewPhoneRecordings":
					params = Ext.urlEncode({'prefixForNewPhoneRecordings': value});
					update = true;
					record.set('prefixForNewPhoneRecordings', value);
					break;
				case "prefixForNewSkypeRecordings":
					params = Ext.urlEncode({'prefixForNewSkypeRecordings': value});
					update = true;
					record.set('prefixForNewSkypeRecordings', value);
					break;
			}
			
			logger.debug('update: ' + update);
			
			if(update) {
				var url = root + 'Request?action=updateTwitterAccount&' + params + '&twitterAccountID=' + twitterAccountID + '&userID=' + userID;
				logger.debug("url: " + url);
				
				Ext.Ajax.request({
					url: url,
					success: function(response) {
						logger.debug("The Twitter account has been updated, record: " + record);
						record.commit(); // Commit the change
					}, 
					failure: function(response) {
						logger.debug("We could not update the Twitter account");
						record.reject(); // reject the changes

						var res = response.responseText;
						
						Ext.Msg.show({
							title:'Unable to update the Twitter account. ',
							msg: res,
							buttons: Ext.Msg.OK,
							animEl: 'elId',
							icon: Ext.MessageBox.ERROR
						});
					},
					scope: this
				});
			}
		}

		logger.endLogGroup(logGroup);
	},
	
	this.addTwitterRecord = function(twitterAccountID, userID, twitterUserID, twitterUsername, accessToken) {
		if(cachedTwitterStore != null && cachedTwitterStore.find('twitterAccountID', twitterAccountID) < 0) {
			var TwitterRecord = this.createTwitterRecord();
			var record = new TwitterRecord({
				twitterAccountID: twitterAccountID,
				userID: userID,
				twitterUserID: twitterUserID,
				twitterUserName: twitterUsername,
				OAuth2Token: accessToken,
				createDate: null,
				notes: '',
				
				pushToTwitterOnNewPublicPhoneRecording: false,
				pushToTwitterOnNewPublicUploadedRecording: false,
				pushToTwitterOnNewPublicSkypeRecording: false,
				pushToTwitterOnNewPublicMicRecording: false,
				
				pushToTwitterOnNewPrivatePhoneRecording: false,
				pushToTwitterOnNewPrivateUploadedRecording: false,
				pushToTwitterOnNewPrivateSkypeRecording: false,
				pushToTwitterOnNewPrivateMicRecording: false,
				
				prefixForNewPhoneRecordings: '',
				prefixForNewSkypeRecordings: '',
				prefixForNewMicRecordings: '',
				prefixForNewUploadRecordings: ''
			});
		
			cachedTwitterStore.add(record);
		}
	},
	
	this.getTwitterAccountStore = function(root, userID) {
		var url = root + 'Request?action=getTwitterAccounts&userID=' + userID;
	
		var store = new Ext.data.Store({
			url: url,
			autoLoad: true,
			sortInfo: {
				field: 'twitterUserName',
				direction: 'ASC'
			},
			reader: new Ext.data.XmlReader({
				record : 'twitterAccount',
				totalRecords: 'totalTwitterAccounts'
			}, this.createTwitterRecord())
		});
		
		return store;
	}
};
// end of file
