
/**
 * @class Voyeur.Tool.DocumentTypeKwicsGrid
 * @description A panel that provides per-document KWIC data in a tabular format.
 * @extends Ext.grid.GridPanel
 * @extends Voyeur.Tool
 * @author Stéfan Sinclair
 * @since 0.1.1
 */
Voyeur.Tool.DocumentTypeKwicsGrid = Ext.extend(Ext.grid.GridPanel, {
	constructor : function(config) {
		Ext.apply(this, new Voyeur.Tool(config, this))
		
		var reader =  new Ext.data.JsonReader(
				{root : 'typeKwics.kwics', totalProperty : 'typeKwics["@totalKwics"]'}
				,Ext.data.Record.create([
					{name : 'type',mapping:'@type'},
					{name : 'left',mapping:'@left'},
					{name : 'middle',mapping:'@middle'},
					{name : 'right',mapping:'@right'},
					{name : 'docId', mapping:'@docId'},
					{name : 'docIndex',mapping:'@docIndex',type : 'int'},
					{name : 'offset', mapping:'@offset',type : 'int'}
				]))
		
		var store = new Ext.data.GroupingStore({
			reader: reader
			,groupField:'docIndex'
			,proxy: new Ext.data.HttpProxy({url:this.getTromboneUrl()})
			,listeners : {
				'beforeload' : {
					fn : function(store, options) {
						Ext.applyIf(options.params, this.getApiParams());
						if (!options.params.corpus) {return false;}
						Ext.apply(options.params, {tool: 'TypeKwics'});
					},
					scope : this
				}
				,'loadexception' : {
					fn: function(conn, proxy, response, error){
						this.alertError(response.responseText);
					}
					,scope : this
				}
			}
			,remoteSort: true
			,sortInfo : {field : this.getApiParamValue('sortBy'), direction : this.getApiParamValue('sortDirection')}
		});
		
		var size = 20;
		
		var xtypePrefix = this.getXType()+'.';

		this.expander = new Ext.grid.RowExpander({context: this.getApiParamValue('preview')});
		this.expander.tromboneUrl = this.getTromboneUrl();
		var forTool = this;
		this.expander.getBodyContent = function(record,index) {
	        var body = '<div id="tmp' + record.id + '">Loading…</div>';
	        Ext.Ajax.request({
	           url: this.tromboneUrl
			   ,params : {
			   		corpus : forTool.getCorpus().getId()
					,tool : 'DocumentReader'
			   		,docId : record.get('docId')
					,offset : record.get('offset')
					,context : forTool.getApiParamValue('preview')
			   }
	           ,disableCaching: true
	           ,success: function(response, options) {
					var data = Ext.util.JSON.decode(response.responseText);
	               Ext.getDom('tmp' + options.objId).innerHTML = Ext.util.Format.htmlEncode(data.documentText['text']).replace(/\n\s*/g,'<br />').replace(new RegExp(options.type,'gi'),"<span class='keyword'>$&</span>");
	           }
	           ,failure: function(error) {
	        	   forTool.alertError(DWRUtil.toDescriptiveString(error, 3));
	           }
			   ,objId: record.id
			   ,type : record.get('type')
	        });

	        return body;
		}
		
		this.expander.beforeExpand = function(record, body, rowIndex){
	        if(this.fireEvent('beforeexpand', this, record, body, rowIndex) !== false){
	            body.innerHTML = this.getBodyContent(record, rowIndex);
	            return true;
	        } else{
	            return false;
	        }
	    }
					
		config.viewConfig = config.viewConfig ? config.viewConfig : {};
		Ext.applyIf(config.viewConfig, {
			forceFit:true,
			emptyText : this.localize('noResults','tool'),
			deferEmptyText: false
			,hideGroupedColumn: true
		})
		
		if (!config.plugins) {config.plugins=[]}
		config.plugins.push(this.expander, new Ext.ux.grid.Favs())

		var currentContext = this.getApiParamValue('context');
		var currentPreview = this.getApiParamValue('preview');

		Ext.applyIf(config, {
			view :  new Ext.grid.GroupingView(config.viewConfig)
			,iconCls : 'table'
			,loadMask : true
			,sm : new Ext.grid.CheckboxSelectionModel(),
			stripeRows : true,
			colModel : new Ext.grid.ColumnModel([
				this.expander		
				,{header : 'Left', css : 'direction: rtl;', dataIndex : 'left', toolTip : Voyeur.localization.get('tool.frequencies_document.term'), renderer : function(val) {val=Ext.util.Format.htmlEncode(val); return val; return "…"+val.substring(val.length-30)}, align : 'right'},
				{header : 'Keyword', dataIndex : 'middle', toolTip : Voyeur.localization.get('tool.frequencies_document.document_index'), renderer : function(val) {return "<span class='keyword'>" +Ext.util.Format.htmlEncode(val) + '</span>';}, align : 'center', width : 50},
				{header : 'Right', dataIndex : 'right', toolTip : Voyeur.localization.get('tool.frequencies_document.document_name'), renderer : function(val) {val = Ext.util.Format.htmlEncode(val); return val; return val.substring(0,30)+"…"}},
				{header : 'Document', dataIndex : 'docIndex', toolTip : Voyeur.localization.get('tool.frequencies_document.document_name'), renderer : {fn: function(val) {return this.getCorpus().getDocument(val).get('title')}, scope: this}, width: 75},
				{header : 'Position', dataIndex : 'offset', toolTip : Voyeur.localization.get('tool.frequencies_document.document_name'), renderer : function(val) {return val}, width : 75, hidden : true}
			]),
			store : store,
			bbar : new Ext.PagingToolbar({
				store : store
		        ,pageSize: size
				,displayInfo: true
				,items : [
					'-',
					{
						text : Voyeur.localization.get(this.xtype+'.context')
						,tooltip : Voyeur.localization.get(this.xtype+'.contextTip')
						,menu : new Ext.menu.Menu({
							items : [
								new Ext.menu.CheckItem({text : '5',checked:currentContext==5,group:'context'})
								,new Ext.menu.CheckItem({text : '10',checked:currentContext==10,group:'context'})
								,new Ext.menu.CheckItem({text : '15',checked:currentContext=15,group:'context'})
								,new Ext.menu.CheckItem({text : '20',checked:currentContext==20,group:'context'})
								,new Ext.menu.CheckItem({text : '25',checked:currentContext==25,group:'context'})
							]
							,listeners : {
								'itemclick' : {
									fn : function(item) {
										this.setApiParams({context: item.text})
										this.getStore().load();
									}
									,scope : this
								}
							}
						})
					}
					,{
						text : Voyeur.localization.get(this.xtype+'.preview')
						,tooltip : Voyeur.localization.get(this.xtype+'.previewTip')
						,menu : new Ext.menu.Menu({
							items : [
								new Ext.menu.CheckItem({text : '10',checked:currentPreview==10,group:'preview'})
								,new Ext.menu.CheckItem({text : '20',checked:currentPreview==20,group:'preview'})
								,new Ext.menu.CheckItem({text : '30',checked:currentPreview==30,group:'preview'})
								,new Ext.menu.CheckItem({text : '40',checked:currentPreview==40,group:'preview'})
								,new Ext.menu.CheckItem({text : '50',checked:currentPreview==50,group:'preview'})
								,new Ext.menu.CheckItem({text : '75',checked:currentPreview==75,group:'preview'})
								,new Ext.menu.CheckItem({text : '100',checked:currentPreview==100,group:'preview'})
								,new Ext.menu.CheckItem({text : '200',checked:currentPreview==200,group:'preview'})
								,new Ext.menu.CheckItem({text : '300',checked:currentPreview==300,group:'preview'})
								,new Ext.menu.CheckItem({text : '400',checked:currentPreview==400,group:'preview'})
								,new Ext.menu.CheckItem({text : '500',checked:currentPreview==500,group:'preview'})
							]
							,listeners : {
								'itemclick' : {
									fn : function(item) {
										this.setApiParams({preview: item.text});
										// look through rows and re-fetch needed previews
										this.getStore().each(function(record, ind) {
											if (this.expander.state[record.id]) {
												this.expander.getBodyContent(record, ind);
											}
										}, this);
									}
									,scope : this
								}
							}
						})
					}
				]
			})
		});
		Voyeur.Tool.DocumentTypeKwicsGrid.superclass.constructor.apply(this, arguments);
		
		this.addListener('CorpusSummaryResultLoaded', function(src, data) {
			this.getStore().load();
		}, this);

		this.addListener('documentTypeSelected', function(src, data) {
			this.setApiParams({docIdType: data.docIdType,  type: null})
			this.getStore().load();
		}, this);

		this.addListener('documentTypesSelected', function(src, data) {
			this.setApiParams({docIdType: data.docIdType,  type: null})
			this.getStore().load();
		}, this);

	}

	,api: {
		start: {'default': 0}
		,limit: {'default': 50}
		,context: {'default': 5}
		,preview: {'default': 50}
		,sortBy: {'default': 'offset'}
		,sortDirection: {'default': 'desc'}
		,type: {'default': null}
		,docIdType: {'default': null}
//		,visibleColumn: {'default': ['type','rawFreq','relativeFreqs']}
	}

	// private localization variables
	,i18n : {
		title : {en: "Keywords in Context"}
		,help : {en: "This tool shows each occurrence of a selected term with some context (words to the left and right of the keyword)."}
		,context : {en: "Context"}
		,contextTip : {en: "This value determines how many words to display on the left and the right of each keyword."}
		,preview : {en: "Preview"}
		,previewTip : {en: "This value determines how many words to display on the left and the right of each keyword in the preview section (the preview is available by expanding the keyword row)."}
		,selectRowsForResults : {en: "Generate results by selecting rows from the <i>Keyword in Context</i> tool."}
	}
});

Ext.reg('voyeurDocumentTypeKwicsGrid', Voyeur.Tool.DocumentTypeKwicsGrid);
