/**
 * @class Voyeur.Tool.CorpusGrid A panel that provides an overview of the current corpus and provides widgets for updating the corpus. 
 * @extends_ext Ext.grid.GridPanel
 * @extends Voyeur.Tool
 * @namespace Voyeur.Tool
 * @author Stéfan Sinclair
 * @since 0.1.1
 */
Voyeur.Tool.CorpusGrid = Ext.extend(Ext.grid.GridPanel, {
	
	corpusLastModified : 0
	
	,constructor : function(config) {
	
		Ext.apply(this, new Voyeur.Tool(config, this));
		
		this.exporters.dhq = this.localize('exportDhq');

		var store = new Ext.data.GroupingStore({
			reader : new Ext.data.JsonReader(
				{root : 'corpus.documents'}
				,Ext.data.Record.create(Voyeur.data.Document.fields)
			)
			,sortInfo : {field : this.getApiParamValue('sortBy'), direction : this.getApiParamValue('sortDirection')}
			,groupField: this.getApiParamValue('author')
		})
		
		var xtypePrefix = config.xtype+'.';
		
		config.viewConfig = config.viewConfig ? config.viewConfig : {};
		Ext.applyIf(config.viewConfig, {
			forceFit:false
//			,autoFill:true
			,emptyText : this.localize('noResults','tool')
			,deferEmptyText: false
			,enableGroupingMenu : true
			,enableGrouping: true
			,showGroupName : false
		})
		
		var sm = new Ext.grid.CheckboxSelectionModel({});
		
		// store a reference to the panel
		var panel = this;

		Ext.applyIf(config, {
			view : new Ext.grid.GroupingView(config.viewConfig)
			,iconCls : 'corpus'
			,stripeRows : true
			,sm : sm
			,enableColumnMove : false
			,autoExpandColumn : this.getId()+'-column-label'
//			,enableDragDrop: true
//			,ddGroup: 'testing'
			,colModel : new Ext.grid.ColumnModel([
// sm
//				{header : this.localize('documentIndex'), dataIndex : 'index', sortable : true, hidden: true, tooltip : this.localize('documentIndexTip')}
				{header : this.localize('documentLabel'), dataIndex : 'id', id : this.getId()+'-column-label', sortable : true, tooltip : this.localize('documentLabelTip'), renderer:function(val) {return panel.getCorpus().getDocument(val).getLabel()}}
				,{header : this.localize('documentTitle'), dataIndex : 'title', id : this.getId()+'-column-title', hidden: true, sortable : true, tooltip : this.localize('documentTitleTip')}
				,{header : this.localize('documentAuthor'), dataIndex : 'author', id : this.getId()+'-column-author', hidden: true, sortable : true, tooltip : this.localize('documentAuthorTip'), renderer: function(val) {return val ? val : '?'}}
				,{header : this.localize('documentTime'), dataIndex : 'timeInMillis', id : this.getId()+'-column-time', hidden: true, sortable : true, tooltip : this.localize('documentTimeTip'), width: 110, renderer: function(val){return new Date(val).format("Y-m-d H:i")}}
				,{header : this.localize('totalDocumentWordTokens'), dataIndex : 'totalWordTokens', sortable : true, tooltip : this.localize('totalDocumentWordTokensTip'), width: 70, renderer: Ext.util.Format.numberRenderer('0,000')}
				,{header : this.localize('totalDocumentWordTypes'), dataIndex : 'totalWordTypes', sortable : true, tooltip : this.localize('totalDocumentWordTypesTip'), width: 70, renderer: Ext.util.Format.numberRenderer('0,000')}
				,{header : this.localize('totalDocumentWordDensity'), dataIndex : 'wordDensity', sortable : true, tooltip : this.localize('totalDocumentWordDensityTip'), width: 70, renderer: Ext.util.Format.numberRenderer('0,000.0')}
			]),
			store : store
			,tbar : [{
				xtype: 'tbtext'
				,text: '&nbsp;'
			}]
		});
		Voyeur.Tool.CorpusGrid.superclass.constructor.call(this, config);

		this.addListener('rowclick', function() {this.fireSelectionChange()}, this)
		this.addListener('headerclick', function(src, grid, rowIndex) {if (rowIndex==0) this.fireSelectionChange();}, this);
		
		/**
		 * @event CorpusSummaryResultLoaded
		 * @type listener
		 */
		this.addListener('CorpusSummaryResultLoaded', function(src, data) {
			if (this.rendered) {this.fireEvent('afterrender', this)};
		}, this);


		this.addListener('afterrender', function(src, params) {
			this.showResults()
		}, this)
		
		this.addListener('export', function(exp) {
	    	 	if (exp=='dhq') {
	        	 	var params = {
    	    	 		corpus : panel.getCorpus().getId()
    	    	 	}
    	    	 	var url = panel.getTromboneUrl();
	    	 		var sm = this.getSelectionModel();
	    	 		var count = sm.getCount();
	    	 		if (count!=1) {
	    	 			return this.alertError({msg: this.localize('selectExactlyOneForExport')});
	    	 		}
	    	 		Ext.applyIf(params, {
	    	 			outputFormat: 'xml'
	    	 			,template : 'docExport2dhqAuthor'
	    	 			,docId: sm.getSelected().get('id')
	    	 		})
	    	 		Ext.applyIf(params, {tool: 'DocumentExporter'})
					var win = window.open(url+'?'+Ext.urlEncode(params));
					if (win) {win.focus();}
	    	 	}
			
		}, this);
		
		this.addListener('sortchange', function(panel, sortInfo) {
			this.setApiParams({sortBy: sortInfo.field, sortDirection: sortInfo.direction});
		}, this);
	}

	,showResults: function() {
		var corpus = this.getCorpus();
		var documents = corpus.getDocuments();
		var records = [];
		documents.each(function(item) {records.push(item.record)});
		this.getStore().removeAll();
		this.getStore().add(records);
		var el = this.getTopToolbar().items.get(0).setText(documents.getCount()+" documents with "+
				Ext.util.Format.number(corpus.get('totalWordTokens'),'000,0')+' tokens and '+
				Ext.util.Format.number(corpus.get('totalWordTypes'),'000,0')+' types');
		// determine if we have authors and if not remove grouping
		if (corpus.getAuthors().length<2) {this.getStore().clearGrouping();}
		this.corpusLastModified = corpus.get('lastModified')
	}
	
	,lastSelectionTime : 0
	,fireSelectionChange : function() {
		var time = new Date().getMilliseconds();
		this.lastSelectionTime=time;
		var me = this;
		setTimeout(function() {if (me.lastSelectionTime == time) {
			documentIds = [];
			records = me.getSelectionModel().getSelections();
			for (var i = 0; i < records.length; i++) {
				documentIds.push(records[i].get('id'))
			}
			if (documentIds.length == 1) {
				/**
				 * @event corpusDocumentSelected
				 * @param {Voyeur.Tool.CorpusGrid} tool
				 * @param {Object} params <ul>
				 * <li><b>docId</b> : String</li>
				 * <li><b>record</b> : {Ext.data.Record}</li>
				 * </ul>
				 * @type dispatcher
				 */
				Voyeur.application.dispatchEvent('corpusDocumentSelected', this, {docId: documentIds[0], record: records[0]});
			}
			else if (documentIds.length > 1) {
				/**
				 * @event corpusDocumentsSelected
				 * @param {Voyeur.Tool.CorpusGrid} tool
				 * @param {Object} params <ul>
				 * <li><b>docId</b> : Array</li>
				 * <li><b>records</b> : {Array}</li>
				 * </ul>
				 * @type dispatcher
				 */
				Voyeur.application.dispatchEvent('corpusDocumentsSelected', this, {docId: documentIds, record: records});
			}
		}}, 1000);
	}
	
	,api: {
		/**
		 * @property sortBy The property to sort results by.
		 * @type String
		 * @default index
		 * @choices index, id, title, author, timeInMillis, totalWordTokens, totalWordTypes, wordDensity
		 */
		'sortBy': {
			'default': 'index'
			,'type': String
			,'required': false
			,'value': null
			,'multiple': false
			,'choices': ['index','id','title','author','timeInMillis','totalWordTokens','totalWordTypes','wordDensity']
		}
		/**
		 * @property sortDirection The direction to sort results in.
		 * @type String
		 * @default ASC
		 * @choices ASC, DESC
		 */
		,'sortDirection': {
			'default': 'ASC'
			,'type': String
			,'required': false
			,'value': null
			,'multiple': false
			,'choices': ['ASC','DESC']
		}
		/**
		 * @property group The property to group results with.
		 * @type String
		 * @choices author, timeInMillis
		 */
		,'group': {
			'default': 'author'
			,'type': String
			,'required': false
			,'value': null
			,'multiple': false
			,'choices': ['author','timeInMillis']
		}
		,toolType: ['Table', 'Corpus']
		,listeners: ['CorpusSummaryResultLoaded']
		,dispatchers: ['corpusDocumentSelected', 'corpusDocumentsSelected']
	}
	
	,thumb: {
		large: 'CorpusGrid.png'
	}
	
	// private localization variables
	,i18n : {
		title : {en: "Corpus"}
	    ,type : {en: "Summary"}
		,documentLabel: {en: "Document Label"}
		,documentLabelTip : {en: "This provides a compact representation of the document position, author, title, and modification time, as available."}
		,documentTitle : {en: "Title"}
		,documentTitleTip : {en: "The document's title."}
		,documentAuthor : {en: "Author"}
		,documentAuthorTip : {en: "The document's author (note that in many cases this may not be known)."}
		,documentTime : {en: "Time"}
		,documentTimeTip : {en: "The document's apparent publication time (note that in many cases the real time may not be known, so the document is assigned the time at which it was analyzed)."}
		,totalDocumentWordTokens : {en: "Tokens"}
		,totalDocumentWordTokensTip : {en: "The total number of word tokens in the document (all words)."}
		,totalDocumentWordTypes : {en: "Types"}
		,totalDocumentWordTypesTip : {en: "The total number of word types in the document (all unique words)."}
		,totalDocumentWordDensity : {en: "Density"}
		,totalDocumentWordDensityTip : {en: "<p>A simple measure of the document's word density the higher the value, the richer the vocabulary. Formula: <pre>(number of types / number of tokens) * 1000</pre>"}
		,help : {en : "<p>This tool shows an overview of the corpus, including each document's title, number of word tokens (total words), number or word types (unique words), and lexical density (the ratio of tokens to types).</p>"}
		,exportDhq: {en: 'TEI (XML)'}
		,exportDhq: {en: 'DHQAuthor (XML)'}
		,selectExactlyOneForExport: {en: 'Please select exactly one document for exporting.'}
	}
});

Ext.reg('voyeurCorpusGrid', Voyeur.Tool.CorpusGrid);



