/**
 * 		Eventhandler working for messages with ICS attachment
<br> 		replacing the attachment name with the METHOD string contained
<br>		in the Vcalendar

@see 	+++2do: 2009-06-20  current version is NOK with inline vcalendar 

		@author gW
		@version	2009-06-20

 */	

var rmFx_icsString = "";
var rmFxEventIcon = "chrome://reminderfox/skin/images/foxy-head-25.png";
var rmFxEventIconSize = 16;



var ICSgContentType;

var ICS_OnMsgLoaded_ORIGINAL = OnMsgLoaded;

var OnMsgLoaded = function(aUrl) {
	ICS_OnMsgLoaded_ORIGINAL.apply(this,arguments);
	
	// "ltnModeBox"  part of Lightning, disabled here to have feature also w.LG
	// if (document.getElementById("ltnModeBox")) 	return;

	try {
	var mimeHdr = aUrl.mimeHeaders;
	} catch (ex) {
		rmFxUtil.dump2Console('promptAlert', " 'aUrl' failed!");
      return;	
	}
	ICSgContentType = mimeHdr.extractHeader("Content-type",false);
	if (ICSgContentType == null) return;
	
	
	rmFxUtil.dump2Console ('rmFxAttachments', "ICSattachment  OnMsgLoaded:" + ICSgContentType);

	// Vcalendar requests seem to be present just in multipart/alternative body
	if (ICSgContentType.indexOf("text/plain") > -1 || ICSgContentType.indexOf("text/html") > -1) 
		return;
	
	// The primary content-type is useful, to find the boundary string, just if the message
	// is multipart/alternative, otherwise we should find the right boundary string in another way
	if (ICSgContentType.indexOf("multipart/alternative") < 0 ) 
		ICSgContentType = null;

	// Postbox needs this timeout, so it can load all ICS attachments to the datapane Events
	setTimeout(ICSparseMsg.start,100);    

	
};


var ICSparseMsg = {
    newAttListner: function() {
        var attListner = {

			scriptStream : null,
        	
            QueryInterface : function(iid)  {
                if (iid.equals(Components.interfaces.nsIStreamListener) ||   
                    iid.equals(Components.interfaces.nsIMsgHeaderSink) ||
                    iid.equals(Components.interfaces.nsISupports))
                 return this;
        
                throw Components.results.NS_NOINTERFACE;
                return 0;
            },
        
			onStartRequest : function (aRequest, aContext) {
					var channel = aRequest.QueryInterface(Components.interfaces.nsIChannel);
					channel.URI.QueryInterface(Components.interfaces.nsIMsgMailNewsUrl);
					channel.URI.msgHeaderSink = this; 

					this.scriptStream = Components.classes['@mozilla.org/binaryinputstream;1']
							.createInstance(Components.interfaces.nsIBinaryInputStream);
			},
		           
			onStopRequest : function (aRequest, aContext, aStatusCode) {
				this.scriptStream = null;
			},

            
            onDataAvailable : function (aRequest, aContext, aInputStream, aOffset, aCount) {
            	
				this.scriptStream.setInputStream(aInputStream);
				rmFx_icsString = this.scriptStream.readBytes(aCount);				
     			rmFxUtil.dump2Console('rmFxAttachments', "ICSparseMsg onDataAvailable"
	     				+ "\n  contentType:" + aRequest.contentType
	     				+ "  aInputStream length:" + aCount);

				var cMethod = "";

		 		// delete all CR characters
		 		rmFx_icsString = rmFx_icsString.replace(new RegExp(/\r/g),"");  
					
				var fnd =  rmFx_icsString.indexOf("METHOD:");                        
				if (fnd != -1) {
                     
			 		rmFx_icsString =  rmFx_icsString.substring(fnd + 7);
					cMethod = rmFx_icsString.substring( 0, rmFx_icsString.indexOf("\n"));

					var theChild = document.getElementById("rmFX_Event");	
					
					if (theChild != null) {
					// replaced the file name
						theChild.attributes["label"].value = "iCal " + cMethod;
					// tag the msg	
						rmFx_msgTAGing("iCal-" + cMethod, true, "#993399");				
			/* ------
			 *  +++2do doesn't work right now
			 		// enable dbl click to work with RmFx on the event
						theChild.setAttribute("ondblclick", "rmFxGetiCalMailed();");
			 ----- */
					}
				}
            },
            
			onStartHeaders: function() {},
    
			onEndHeaders: function() {},
			
			processHeaders: function(headerNameEnumerator, headerValueEnumerator, dontCollectAddress) {},
 
			
			
			// The extension can work because natively Thunderbird
			// collect in this functions also multipart/alternative parts
			// even if they are not real attachments

			handleAttachment: function(contentType, url, displayName, uri, isExternalAttachment) {	
			rmFxUtil.dump2Console ('rmFxAttachments', "handleAttachment: "
			         + "\n" + contentType + "    " + displayName);
   
           		if ( displayName.indexOf(".vcs") < 0 
           				&& displayName.indexOf(".ics") 
           				&& (contentType == "text/calendar" || contentType =="text/x-calendar") ) {
   
					var childList = document.getElementById('attachmentList');
						
					//  Postbox special
					if (childList == null)  
						childList = document.getElementById('dataPaneEventList');

					var nodes = childList.childNodes.length
						
					for (var i=0; i< nodes; i++) {
						var cName = childList.childNodes[i].attachment.displayName;
						
						if (cName.toLowerCase().indexOf(".ics") > -1) {
							childList.childNodes[i].attributes["image"].value
								 = rmFxEventIcon + "?size=" + rmFxEventIconSize + "&contentType=text/calendar";

							childList.childNodes[i].id ="rmFX_Event"
						}
					}
					this.index++;
				}
            },
            
            onEndAllAttachments: function() {},      
            onEndMsgDownload: function(url) {},      
            onEndMsgHeaders: function(url) {},        
            onMsgHasRemoteContent: function(aMsgHdr) {},       
            getSecurityInfo: function() {},      
            setSecurityInfo: function(aSecurityInfo) {},     
            getDummyMsgHeader: function() {}
        };
        return attListner;
        
    },
     
    start: function() {
    	
    	rmFx_icsString = "";
    	
    /* -----	
    	if ((gRmFx_Messenger == "TB3") || (gRmFx_Messenger == "SM2")) {
    		var msgUri =  gFolderDisplay.selectedMessageUris[0];
		}  else {
			var msgUri = GetLoadedMessage();
		}
	 ----- */
      try {  // instead of using gRmFx_Messenger ... 
         var msgUri =  gFolderDisplay.selectedMessageUris[0];
      } catch (ex) {
         var msgUri = GetLoadedMessage();      	
      }

      rmFxUtil.dump2Console ('rmFxAttachments', "rmFx_icsString  msgUri:" +  msgUri);
            
      if (msgUri != null) {
			var mms = messenger.messageServiceFromURI(msgUri)
				.QueryInterface(Components.interfaces.nsIMsgMessageService);
			var streamListner = ICSparseMsg.newAttListner(); 
			streamListner.index = 0;  
			var newUri = mms.streamMessage(msgUri, streamListner, null, null, true, "filter");
      }
   }
}
/**
 * 	Read the whole selected message (including attachments) to a string
 * 
<p> 	@return	content	, if read fails: alert and return null
 */
function rmFxReadSelectedMsg () {
	var content = "";
	  var MessageURI = GetFirstSelectedMessage();
	  var MsgService = messenger.messageServiceFromURI(MessageURI);
	  
	  var MsgStream =  Components.classes["@mozilla.org/network/sync-stream-listener;1"]
	                            .createInstance();
	  var consumer = MsgStream.QueryInterface(Components.interfaces.nsIInputStream);
	  
	  var ScriptInput = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance();
	  var ScriptInputStream = ScriptInput.QueryInterface(Components.interfaces.nsIScriptableInputStream);
	  
	  ScriptInputStream.init(consumer);
	  
	  try {
	    MsgService.streamMessage(MessageURI, MsgStream, msgWindow, null, false, null);
	  } catch (ex) {
	    alert(" Error: "+ex);
	    return null;
	  }
	  ScriptInputStream .available();
	  while (ScriptInputStream .available()) {
	    content = content + ScriptInputStream .read(512);
	  }
	  
	  return content;
}
	