//------------------------------------------------------------------------------
// <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 AggregateForumRssHandler.
	/// </summary>
	public class AggregateForumRssHandler : BaseForumSyndicationHandler
	{
		public AggregateForumRssHandler()
		{
			//
			// TODO: Add constructor logic here
			//
		}

		protected ThreadViewMode CurrentMode = ThreadViewMode.Default;

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

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

			// Do we have a mode argument?
			if (csContext.Context.Request.QueryString["mode"] != null) 
				CurrentMode = (ThreadViewMode) int.Parse(csContext.Context.Request.QueryString["mode"]);

			base.ProcessFeed();
		}

		protected override Section GetCurrentSection
		{
			get { return null; }
		}

		protected override string CacheKey
		{
			get { return string.Format("ForumAggregate:{0}:{1}", CSContext.Current.SiteSettings.SettingsID, CurrentMode.ToString()); }
		}

		protected override CachedFeed BuildFeed()
		{
			ArrayList threads = null;

			ForumThreadQuery query = new ForumThreadQuery();
			query.ForumID = -1;
			query.PageSize = ForumConfig.RssDefaultThreadsPerFeed;
            query.IgnoreStickyPosts = true;

			switch (CurrentMode)
			{
				case ThreadViewMode.Active:
					query.ActiveTopics = true;
					threads = Threads.GetThreads(query).Threads;
					break;

				case ThreadViewMode.Unanswered:
					query.UnAnsweredOnly = true;
					threads = Threads.GetThreads(query).Threads;
					break;

				case ThreadViewMode.Videos:
					query.PostMedia = PostMediaType.Video;
					threads = Threads.GetThreads(query).Threads;
					break;

				default:
					threads = Threads.GetThreads(query).Threads;
					break;
			}

			AggregateForumRssWriter writer = new AggregateForumRssWriter(threads, CurrentMode, this.BaseUrl);

			DateTime dt =  threads.Count > 0 ? ((Post)threads[threads.Count -1]).PostDate : DateTime.Now;

			return new CachedFeed(dt, null, writer.GetXml());
		}
	}
}
