/**
 * 	rmFxDragDrop.js
 * 
 *<br>   Drag&Drop	of 	'iCal' OS-files, iCal/ICS-message attachments, text, url 
 *  				onto the TB statusbarpanel  (ReminderFox section)
 *
 *<br>   supporting TB2.0.x and up to Fx3.0.x

 * @since
 *   2009-01-04  	new		FX3.1
 *  	
*/
 
const rmFx_statObserver = {
	init: function () {
	  this.flavour = "rmFx";
	  this.statusbarPanel = "reminderFox-statusLabel";		//id of the statusbarpanel to drag
	  this.statbar = "status-bar";								//name of statusbar
	},
	
	getSupportedFlavours: function () {
		var flavours = new FlavourSet();
			flavours.appendFlavour("text/html");	
			flavours.appendFlavour("text/x-moz-message");
			flavours.appendFlavour("text/x-moz-url");
			flavours.appendFlavour("application/x-moz-file");
			flavours.appendFlavour("text/unicode");
		return flavours;
	},


	onDragOver: function(aEvent, aFlavour, aDragSession) {
		// ("rmFx ... onDragOver");
	},

	onDrop: function (aEvent,dropdata,aDragSession){

		aEvent.preventDefault();
		var dropFlavour = dropdata.flavour.contentType;
		
		// get dat awith 'best' estimate
		var transferable = Components.classes["@mozilla.org/widget/transferable;1"]
					.createInstance(Components.interfaces.nsITransferable);
			transferable.addDataFlavor("text/x-moz-url");
			transferable.addDataFlavor("application/x-moz-file")
			transferable.addDataFlavor("text/html");
			transferable.addDataFlavor("text/x-moz-message");
			transferable.addDataFlavor("text/unicode");
		aDragSession.getData(transferable, 0);

		var dataObj  = new Object();
		var bestFlavour = new Object();
		var len = new Object();
		transferable.getAnyTransferData(bestFlavour, dataObj, len);
		dataObj = dataObj.value.QueryInterface(Components.interfaces.nsISupportsString);
		var source = dataObj.data.substring(0, len.value);		
		
		try {
			// build a plain-text version of the drag data
			var transX = Components.classes["@mozilla.org/widget/transferable;1"]
						.createInstance(Components.interfaces.nsITransferable);
				transX.addDataFlavor("text/unicode");	
			aDragSession.getData(transX, 0);	
	
			var dataObjX  = new Object();
			var bestFlavourX = new Object();
			var lenX = new Object();
			transX.getAnyTransferData(bestFlavourX, dataObjX, lenX);
			dataObjX = dataObjX.value.QueryInterface(Components.interfaces.nsISupportsString)
			var sourceX =  dataObjX.data.substring(0, lenX.value);	
		} catch (ex) {}
        /* ---
        try {  // sorry only working for 'messenger' apps 
            // build a plain-text version of the drag data		
    		var sx = htmlToPlainText(source) // aHtml
        } catch (ex) {}     
		--------- */
		// ..				
		var url = source.split("\n")[0].toLowerCase();
		var url0 = source.split("\n")[0];
	
		// get msgHdr info from 'CurrentHeader'  
		// 	NOT used if D&D doesn't come from a message  
		var ret = "\n";
		var msgInfo = "";		
		var messageId = null;
		try {  // check msg Hdr -- if valid : set msg info from header !!
			var msgInfo = "[mail] " + currentHeaderData.subject.headerValue + ret
					+ "     " +reminderFox_getBundle().getString("rf.add.mail.message.date") + ": " + currentHeaderData.date.headerValue + ret
					+ "     " +reminderFox_getBundle().getString("rf.add.mail.message.sender") + ": " + currentHeaderData.from.headerValue + ret
					+ "     " +reminderFox_getBundle().getString("rf.add.mail.message.recipients") + ": " + currentHeaderData.to.headerValue + ret	;

		    var messageId = currentHeaderData["message-id"].headerValue;
		    messageId = messageId.replace(new RegExp(/\"/g),"");
		} catch (e) {}

	
		// 1. / 'Add Reminder' for a message on the mail:3pane 	
		if (bestFlavour.value == "text/x-moz-message") {		
			if ((/^imap-message:/.test(url)) || (/^mailbox-message:/.test(url))) {
				var rv = rmFxGetiCalMailed("1.");
			}
		} else 
		
		// 6.	'Import iCal data' from external data source /applications 
		//			supporting D&D (source data encoding required: unicode/utf-8)
		//			--  from open files with selecting iCal data
		//gW_D&D of files with TODO only   2009-12-12
		if (bestFlavour.value == "text/unicode") {	
			if ((source.indexOf("BEGIN:VCALENDAR") != -1) && 
					((source.indexOf("VEVENT") != -1) || (source.indexOf("VTODO") != -1))){
				
				if ( msgInfo == "") { 
					msgInfo = " [" + reminderFox_getBundle().getString("rf.schedule.import.dand") + "]";
				}
				rmFxGetiCalFromTextBody(source, msgInfo, "6.");
			} else {
				// "text/unicode without vCalendar data"
				rmFx_rm4plainText(source, null);
			}
		} 

		
		if (dropFlavour =="text/html") { // 2. 3. 7. 8.

			// 2. 'Subscribe' from a URL containing an .ics file containing iCal data
			if (((url.indexOf('http') == 0) || (url.indexOf('webcal:')== 0)) &&
				 (url.indexOf(".ics") == url.length - 4)) {
				// gW 2008-10-30 'subscribeOradd'
				//	reminderFox_subscribeWithReminderFox(url0);
					rmFxSubscribeOrAddReminder(url0);					
			} else {
				
				//	8.	'add reminder' for URL link
				if (url.indexOf('http') == 0) {
					if (messageId != null) {						
						source = msgInfo +"\n \n"+ url0;		// 8b.  .. insert TB message infos
					}													// 		spc between CR to not convert to one \n
					rmFx_rm4plainText(source, messageId);	// 8a.  .. coming from FX				
				} else {
					
					// 3.	'Import iCal data' received with a message containing iCal data 
					//		--  from message body with displayed and selecetd iCal data (select 'inline' display of message)
					//gW_D&D of files with TODO only   2009-12-12
					//gW_D&D use sourceX (text/unicode) 
					if ((sourceX.indexOf("BEGIN:VCALENDAR") != -1) && 
							((sourceX.indexOf("VEVENT") != -1) || (sourceX.indexOf("VTODO") != -1))){															
						
						if ( msgInfo == "") { 
							msgInfo = " [" + reminderFox_getBundle().getString("rf.schedule.import.dand") + "]";
						}
						//  extract iCalendar string !!   from 'dropdata.supports.data'						
						var rv = rmFxGetiCalFromTextBody(sourceX, msgInfo, "3.");  // , messageId);
						
						if (rv == true) { rmFx_msgTAGing('iCal-' + rmFx_iCalMETHOD, true, '#3333FF');	};		// tag with METHOD 
					} else {
					// 7. 'Add Reminder' for a 'selected' text (7a. FX, 7b. TB)
					
						if (messageId != null) {						// 7a.  .. coming from FX
							source = msgInfo +"\n \n"+ source;		// 		spc between CR to not convert to one \n																			
						}														
						rmFx_rm4plainText(sourceX, messageId); 		// 7b.  .. insert TB message infos	
						}
					}
				}
			}

		// 4.	'Import iCal data' received with a message containing iCal data 
		//		--  from '.ics' attachment
		// 5.	'Import iCal data' from external data source /applications 
		//		supporting D&D (source data encoding required: unicode/utf-8)
		//		--  from OS files (like from file manager/explorer)
		
		if (/^imap:/.test(url) || /^mailbox:/.test(url)) {  	// form attachment
			var rv = rmFxGetiCalMailed("4.5. mail/imap");
					
		} else if (/^file:/.test(url)) {				// form file on desktop / explorer
			var filePath = urlToPath(url0);        //gW_DDlinux  2010-08-27 
			if (filePath != null) {		
				var localFile = Components.classes["@mozilla.org/file/local;1"]
						.createInstance(Components.interfaces.nsILocalFile);                              
				localFile.initWithPath(filePath);
		//gW_D&D of files with TODO only   2009-12-12
				var inputStream = reminderFox_readInFileContents(localFile);
				
				
				if ((inputStream.indexOf("BEGIN:VCALENDAR") != -1) && 
						((inputStream.indexOf("VEVENT") != -1) || (inputStream.indexOf("VTODO") != -1))){
					var mInvitation = reminderFox_getBundle().getString("rf.schedule.import.dataof") + " File: [" + filePath + "]";
					rmFxGetiCalFromTextBody(inputStream, mInvitation, "4./5. file");
				}
			}
		}
	}
}
window.addEventListener('load', rmFx_statObserver.init, false); 
	
function urlToPath (aPath) {
	var rv = null;
	if (!aPath || !/^file:/.test(aPath))
		return rv;
	var ph = Components.classes["@mozilla.org/network/protocol;1?name=file"]
		.createInstance(Components.interfaces.nsIFileProtocolHandler);
	rv = ph.getFileFromURLSpec(aPath).path;
	return rv;
}


function rmFx_rm4plainText(pText, msgId) {		// if msgId --> tag msg
    
	var subject = null; var notes = null;	var url = null;
	
	if ( pText != null ) {	
		pText = reminderFox_trim(pText);
		pText = pText.replace(new RegExp(/&nbsp;/g)," ");
		pText = pText.replace(new RegExp(/\n\n/g),"\n ");
		pText = pText.replace(new RegExp(/\t/g),"");
		pText = pText.replace(new RegExp(/  /g)," ");
		
		var aText = pText.split("\n");

		for (var i=0; i < aText.length; i++) {
				
			if ((aText[i].indexOf('http') != -1) && (url == null)) {
				// strip out the link 
				var a = aText[i].indexOf('http');
				var e = aText[i].substring(a + 1).indexOf(' ');
				if (e == -1) {
					url = aText[i].substring(a);
				} else {
					url = aText[i].substring(a, a + e + 1);
				}
			}
			if ((aText[i] != "") && (subject == null)) {
				if (aText[i] != url) {subject = aText[i];}
			}				 
		}
		if (subject == null) {subject = url;}
	}
	var newDate = new Date();
	newDate.setDate( newDate.getDate() );  // default to using today's date for reminder
	var reminderId =reminderFox_generateUniqueReminderId( newDate );
	var newReminderToBeAdded = new ReminderFoxEvent( reminderId, newDate, subject );

	if ( pText.length > 0) {
		newReminderToBeAdded.notes = aText.join("\n");
	}
	if (newReminderToBeAdded.notes == subject) {
		newReminderToBeAdded.notes = null;
	}
	
	if ( msgId != null ) {
		newReminderToBeAdded.messageID = msgId;	
	}
	if ( url != null ) {
		newReminderToBeAdded.url = url;
	}
	var rv = reminderFox_addReminderHeadlessly( newReminderToBeAdded );
	if (rv && msgId != null) {rmFx_msgTAGing("Reminderfox", true, "#993399")};
}	


 /**
  * Convert HTML into text/plain 
  *    .. sorry only for 'messenger'
  * @param {String} aHtml A string containing the HTML that's to be converted.
  * @return {String} A text/plain string suitable for insertion in a mail body.
  */
 function htmlToPlainText(aHtml) {

   let fields = Components.classes["@mozilla.org/messengercompose/composefields;1"]
                   .createInstance(Components.interfaces.nsIMsgCompFields);
   fields.body = aHtml;
   fields.forcePlainText = true;
   fields.ConvertBodyToPlainText();
   return fields.body;
}
