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

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

namespace CommunityServer.Blogs.Components
{
	/// <summary>
	/// Summary description for AggregateRssHandler.
	/// </summary>
	public class AggregateRssHandler : BaseWeblogSyndicationHandler
	{
		public AggregateRssHandler()
		{
		}

        protected Group CurrentGroup = null;
        protected BlogMirrorDisplayType DisplayType = BlogMirrorDisplayType.AllBlogs;
		protected string[] Tags = null;
		protected bool AndTags = false;

        protected bool HasGroup
        {
            get
            {
                return CurrentGroup != null;
            }
        }

        protected bool FilterByDefaultTags
        {
            get{ return Context.Request.QueryString["unfiltered"] == null; }
        }

        protected override void ProcessFeed()
        {
            int groupID = Globals.SafeInt(Context.Request.QueryString["GroupID"], -1);
            if (groupID > -1)
                CurrentGroup = WeblogGroups.GetWeblogGroup(groupID, true, false);

			// Check to see if a BlogMirrorDisplayType was given in the URL.
			if (Context.Request.QueryString["type"] != null)
			{
				try
				{
					DisplayType = (BlogMirrorDisplayType)System.Enum.Parse(typeof(BlogMirrorDisplayType), Context.Request.QueryString["type"], true);
				}
				catch {}
			}

			if (CSContext.Current.Tags != null)
			{
				this.Tags = CSContext.Current.Tags;
				if (Context.Request.QueryString["andTags"] != null)
				{
					double andTags = 0;
					if (Double.TryParse(Context.Request.QueryString["andTags"], System.Globalization.NumberStyles.Integer, null, out andTags))
						this.AndTags = Convert.ToBoolean((int)andTags);
				}
			}

            if(FilterByDefaultTags)
            {
                WeblogConfiguration config = WeblogConfiguration.Instance();

                if(this.Tags == null || this.Tags.Length == 0)
                    this.Tags = config.DefaultAggregateTags;
                else if(WeblogConfiguration.Instance().HasAggregateTags)
                {
                    string[] newTags = new string[this.Tags.Length + config.DefaultAggregateTags.Length];
                    Array.Copy(this.Tags,newTags,this.Tags.Length);
                    Array.Copy(config.DefaultAggregateTags,0,newTags,Tags.Length,config.DefaultAggregateTags.Length);

                    this.Tags = newTags;
                }

            }

				


            base.ProcessFeed ();
        }

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


	    protected override string CacheKey
	    {
	        get
	        {
				StringBuilder sb = new StringBuilder();
				sb.AppendFormat("WeblogAggregate:{0}:Type:{1}", CSContext.Current.SiteSettings.SettingsID, (int)DisplayType);

				if (HasGroup)
					sb.AppendFormat(":GroupID{0}", CurrentGroup.GroupID);
				else
					sb.Append(":IndividualRss");

				if (Tags != null && Tags.Length > 0)
					sb.AppendFormat(":TagsRss:{0}:AndTags:{1}", String.Join(",", Tags), AndTags);

				return sb.ToString();
	        }
	    }

	    protected override CachedFeed BuildFeed()
	    {
            BlogThreadQuery query = BlogThreadQuery.CreateNewAggregateQuery();
			query.BlogPostType = BlogPostType.Post;
            query.PageIndex = 0;
            query.PageSize = WeblogConfiguration.Instance().AggregatePostCount;
			query.FirstPageOnly = false;
			query.PostConfig = BlogPostConfig.IsCommunityAggregated | BlogPostConfig.IsAggregated;
            query.BlogMirrorDisplayType = DisplayType;

            if(HasGroup)
                query.GroupID = CurrentGroup.GroupID;


            if (Tags != null && Tags.Length > 0)
            {
                query.Tags = Tags;
                query.LogicallyOrTags = !AndTags;
            }


            ThreadSet threads = WeblogPosts.GetBlogThreads(query, true, true);

			ArrayList posts = threads.Threads;

			BaseRssWriter writer = new AggregateRssWriter(posts, this.CurrentGroup, this.BaseUrl);
			DateTime dt = posts.Count > 0 ? ((WeblogPost)posts[0]).PostDate : DateTime.Now;
            
            return new CachedFeed(dt,null,writer.GetXml());
	    }
	}
}
