//
// Beagle
//
// FilterMail.cs : MailDir filter.
//
// Author :
//      Noam Rathaus <rathaus@gmail.com>
//
// Copyright (C) 2005 Noam Rathaus
//
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

using Beagle.Util;

namespace Beagle.Filters {

	public class FilterMail : Beagle.Daemon.Filter {
		StreamReader reader;
		FileInfo file;

		public FilterMail ()
		{
			// Make this a general troff filter.
			AddSupportedMimeType ("text/x-mail");
			AddSupportedMimeType ("message/rfc822");
		}
		
		protected void ParseMailFile (StreamReader reader)
		{
			string str;
			bool FirstEmpty = false;
			bool Mixed = false;
			// @ is for making path writing easier... no need to escape
			Regex headerRE = new Regex (@"(^From: (?<From>.*?)$)|" +
										@"(^To: (?<To>.*?)$)|" +
										@"(^Subject: (?<Subject>.*?)$)|" +
										@"(^Date: (?<Date>.*?)$)|" +
										@"(^Content-Type: (?<ContentType>.*?)$)"
										);

			if (file.FullName.IndexOf("sent-mail") != -1)
				AddProperty (Beagle.Property.NewFlag ("fixme:isSent"));

			while (((str = reader.ReadLine ()) != null) && (Mixed == false)) {
					// System.Console.WriteLine("{0} << {1}", str.Length, str);
					if (str.Length == 0 && FirstEmpty == true)
					{
						break;
					}
					if (str.Length != 0 && FirstEmpty == true)
					{
						FirstEmpty = false;
					}
					if (str.Length == 0 && FirstEmpty == false)
					{
						FirstEmpty = true;
					}

					MatchCollection matches = headerRE.Matches (str);
					if (matches.Count != 1) {
						//Console.Error.WriteLine ("Expected 1 per line match but found {0} matches",
						//			  matches.Count);
						continue;
					}
					foreach (Match theMatch in matches) {
						Console.WriteLine("theMatch: {0}", theMatch);
						if (theMatch.Groups ["ContentType"].Value == "Multipart/Mixed;")
						{
							Mixed = true;
							break;
						}
						if (theMatch.Groups ["Subject"].Value != "") {
							Console.WriteLine("Added Subject ({0})", theMatch.Groups ["Subject"].Value);
							AddProperty (Beagle.Property.New ("dc:title", theMatch.Groups ["Subject"].Value));
							AddProperty (Beagle.Property.New ("fixme:subject", theMatch.Groups ["Subject"].Value));
						}
						if (theMatch.Groups ["From"].Value != "") {
							Console.WriteLine("Added From ({0})", theMatch.Groups ["From"].Value);
							if (file.FullName.IndexOf("sent-mail") == -1)
							{
								Console.WriteLine("Non sent-mail");
								AddProperty (Beagle.Property.New ("fixme:from", theMatch.Groups ["From"].Value));
							}
							else
							{
								Console.WriteLine("Sent-mail style");
								AddProperty (Beagle.Property.NewKeyword ("fixme:from", "local@localhost"));
							}
						}
						if (theMatch.Groups ["To"].Value != "") {
							Console.WriteLine("Added To ({0})", theMatch.Groups ["To"].Value);
							AddProperty (Beagle.Property.New ("fixme:to", theMatch.Groups ["To"].Value));
						}
						if (theMatch.Groups ["Date"].Value != "") {
							Console.WriteLine("Added Date ({0})", theMatch.Groups ["Date"].Value);
							string date = theMatch.Groups ["Date"].Value;
							Console.WriteLine("Date: {0}", date);
							DateTime timestamp = Rfc822DateTime.FromString(date);
							if (file.FullName.IndexOf("sent-mail") != -1)
								AddProperty (Beagle.Property.NewDate ("fixme:sentdate", timestamp));
							else
								AddProperty (Beagle.Property.NewDate ("fixme:received", timestamp));
						}
					}
			}
			Finished ();
		}

		override protected void DoOpen (FileInfo info)
		{
			Stream stream;
			stream = new FileStream (info.FullName,
						 FileMode.Open,
						 FileAccess.Read,
						 FileShare.Read);
			reader = new StreamReader (stream);
			file = info;
		}
		override protected void DoPull ()
		{
			ParseMailFile (reader);
		}
	}
}
