/**
 * @class Voyeur.Tool.CorpusGrid
 * @description A panel that provides an overview of the current corpus and provides widgets for updating the corpus.
 * @extends Ext.grid.GridPanel
 * @extends 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('direction')}
			,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);
		this.addListener('CorpusSummaryResultLoaded', function(src, data) {
			if (this.rendered) {this.fireEvent('afterrender', this)};
		}, this);

//		this.addListener('CorpusGridBootstrap', function(src, params) {
//			if (params.sortBy) {
//				this.store.sort(params.sortBy, params.direction ? params.direction : null);
//			}
//			else {this.store.sort('index', 'ASC')}
//			if (!this.getCorpus().get('lastModified') || this.corpusLastModified < this.getCorpus().get('lastModified')) {
//				this.update({params : params, tool : 'CorpusSummary'});
//			}
//		}, this)
		this.addListener('afterrender', function(src, params) {
			this.showResults()
			/*
			var destGridDropTargetEl = this.getView().el.dom.childNodes[0].childNodes[1]

	      		var destGridDropTarget = new Ext.dd.DropZone(destGridDropTargetEl, {
	      			ddGroup    : 'testing',
	//      			copy       : false,
	      			onNodeDrop : function(ddSource, e, data){
	      				
	      				console.warn(ddSource,e,data);
	      				// Generic function to add records.
	      				function addRow(record, index, allItems) {
	      					
	      					// Search for duplicates
	      					var foundItem = secondGridStore.find('name', record.data.name);
	      					// if not found
	      					if (foundItem  == -1) {
	      						secondGridStore.add(record);
	      						// Call a sort dynamically
	      						secondGridStore.sort('name', 'ASC');
	      				
	      						//Remove Record from the source
	      						ddSource.grid.store.remove(record);
	      					}
	      				}
	      				// Loop through the selections
	      				Ext.each(ddSource.dragData.selections ,addRow);
	      				return(true);
	      			}
	      		}); 
			console.warn(destGridDropTarget)
			*/
		}, 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, direction: 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().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) {
				Voyeur.application.dispatchEvent('corpusDocumentSelected', this, {docId: documentIds[0]}, records[0]);
			}
			else if (documentIds.length > 1) {
				Voyeur.application.dispatchEvent('corpusDocumentsSelected', this, documentIds, records);
			}
		}}, 1000);
	}
	
	,api: {
		'sortBy': {
			'default': 'index'
			,'type': String
			,'required': false
			,'value': null
			,'multiple': false
			,'choices': ['index','id','title','author','timeInMillis','totalWordTokens','totalWordTypes','wordDensity']
		}
		,'direction': {
			'default': 'ASC'
			,'type': String
			,'required': false
			,'value': null
			,'multiple': false
			,'choices': ['ASC','DESC']
		}
		,'group': {
			'default': 'author'
			,'type': String
			,'required': false
			,'value': null
			,'multiple': false
			,'choices': ['author','timeInMillis']
		}
	}
	
	// private localization variables
	,i18n : {
		title : {en: "Corpus"}
		,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><p>The buttons at the bottom allow you to modify the corpus by adding and removing texts.</p>"}
		,exportDhq: {en: 'TEI (XML)'}
		,exportDhq: {en: 'DHQAuthor (XML)'}
		,selectExactlyOneForExport: {en: 'Please select exactly one document for exporting.'}
	}
});

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


