//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System.Xml;
using CommunityServer.Components;
using System.Collections;

namespace CommunityServer.Files.Components
{

	/// <summary>
	/// Summary description for WeblogEmailNotificationModule.
	/// </summary>
	public class FileEmailNotificationModule : ICSModule
	{
		public FileEmailNotificationModule()
		{
		}

		public void Init(CSApplication csa, XmlNode node)
		{
			csa.PostPostUpdate +=new CSPostEventHandler(csa_PostPostUpdate);
		}

		private void csa_PostPostUpdate(IContent content, CSPostEventArgs e)
		{
			EntryComment c = content as EntryComment;
			if(c != null && ProcessEmail(c))
			{
				// Retrieve the entry for this comment
				Entry parent = Entries.GetEntry(c.ParentID);
			
				// Send email notification to Folder Owner if requested
				if (parent.EnableCommentNotification)
					FileEmails.FolderCommentNotification(c, parent);
				
				// Process email subscriptions only if post is approved
				if (c.IsApproved)
					FileEmails.EntryTracking(c, parent);
			}
			

			Entry entry = content as Entry;
			if (entry != null && ProcessEmail(entry))
			{
				if (entry.EnableEntryNotification)
					FileEmails.FolderEntryNotification(entry);
			}
		}

		private bool ProcessEmail(EntryComment c)
		{
			CSContext cntx = CSContext.Current;
			ArrayList commentsProcessed = (ArrayList) cntx.Items["FileGalleryCommentNotifications"];
			if (commentsProcessed == null)
				commentsProcessed = new ArrayList();

			if (commentsProcessed.Contains(c.PostID))
				return false;
			else
			{
				commentsProcessed.Add(c.PostID);
				cntx.Items["FileGalleryCommentNotifications"] = commentsProcessed;
				return true;
			}
		}

		private bool ProcessEmail(Entry e)
		{
			CSContext cntx = CSContext.Current;
			ArrayList entriesProcessed = (ArrayList) cntx.Items["FileGalleryEntryNotifications"];
			if (entriesProcessed == null)
				entriesProcessed = new ArrayList();

			if (entriesProcessed.Contains(e.PostID))
				return false;
			else
			{
				entriesProcessed.Add(e.PostID);
				cntx.Items["FileGalleryEntryNotifications"] = entriesProcessed;
				return true;
			}
		}
	}

}
