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

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

namespace CommunityServer.Blogs.Components
{

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

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

		private void csa_PostPostUpdate(IContent content, CSPostEventArgs e)
		{
			
			WeblogPost wp = content as WeblogPost;
			if(wp != null && e.State != ObjectState.Delete)
			{

				if (!wp.Section.BlockSpamFeedbackNotifications || ((wp.PostStatus & PostStatus.Spam) != PostStatus.Spam))
                {
			
					// Retrieve the parent if this is feedback. Do it here so we don't need 2 DB hits
					WeblogPost parent = null;
					if (wp.IsFeedback)
						parent = WeblogPosts.GetPost(wp.ParentID, false, true, true);
					
					// Send email notification to Blog Owner depending on FeedbackNotificationType setting
					if (e.State == ObjectState.Create)
					{
						switch (wp.FeedbackNotificationType)
						{
							case FeedbackNotificationType.AllFeedback:
							{
								if (wp.IsFeedback)
									WeblogEmails.WeblogFeedbackNotification(wp, parent);

								break;
							}

							case FeedbackNotificationType.AllComments:
							{
								if (wp.BlogPostType == BlogPostType.Comment)
									WeblogEmails.WeblogFeedbackNotification(wp, parent);

								break;
							}
				
						}
					}
					
                    // Process email subscriptions only once (when approved for the first time)
					// Note: EnableExternalNotificatons is not persisted. 
					//		It gets set to true only in the WeblogPosts Add & Update methods.
                    if (wp.EnableExternalNotificatons)
                        WeblogEmails.WeblogTracking(wp, parent);

                }
			}
		}


	}

}
