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

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

namespace CommunityServer.Discussions.Components
{
	/// <summary>
	/// Summary description for ForumCommentRssHandler.
	/// </summary>
	public class ForumCommentRssHandler : BaseForumSyndicationHandler
	{

		public ForumCommentRssHandler()
		{
		}

		/// <summary>
		/// The key used to lookup the feed uniquely in the cache.
		/// </summary>
		/// <returns></returns>
		protected override string CacheKey
		{
			get { return string.Format("CommentRss-PostID:{0}",  CSContext.Current.PostID); }
		}


		protected override void ProcessFeed()
		{
			CSContext csContext = CSContext.Current;

			if(csContext.PostID <= 0)
				Globals.Return404(Context);

			if(!ForumConfig.EnableForumsRSS)
			{
				Context.Response.Write("Error - RSS Is Not Enabled.");
				return;
			}

			base.ProcessFeed ();
		}


		protected override CachedFeed BuildFeed()
		{
			PostSet ps = Posts.GetPosts(CSContext.Current.PostID, 0, ForumConfig.RssDefaultThreadsPerFeed, 0, 0);
			ps.Organize();

			ForumPost fp = ps.ThreadStarter as ForumPost;

			//If we do not have a post, there is not much we can do
			if(fp == null)
			{
				Context.Response.End();
				return null;
			}

			DateTime dt = (ps.Replies != null &&  ps.Replies.Count > 0) ? ((ForumPost)(ps.Replies[ps.Replies.Count -1])).PostDate : fp.PostDate;

			ForumCommentRssWriter writer = new ForumCommentRssWriter(fp, ps.Replies, this.CurrentSection, this.BaseUrl);
			return new CachedFeed(dt, dt.ToString(), writer.GetXml());
		}


	}
}
