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

using System;
using System.Collections;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using CommunityServer.Blogs.Components;
using CommunityServer.Components;
using CommunityServer.Configuration;
using CommunityServer.Controls;

namespace CommunityServer.Blogs.Controls
{
	/// <summary>
	/// Summary description for AggregatePostList.
	/// </summary>
	public class AggregatePostList : WeblogBaseTemplatedWebControl
	{
		public AggregatePostList()
		{
			//
			// TODO: Add constructor logic here
			//
		}

	    AggregateList posts = null;
        Literal title = null;
        BlogThreadSortBy sortBy = BlogThreadSortBy.MostRecent;
		private int pageSize = -1;
		private bool pageOnPostBackOnly = false;
        private bool includeCategories = false;
		private bool includeAutodiscovery = false;
        private bool scorePosts = false;

		/// <summary>
		/// Property to control the number of elements that are rendered for each page in the repeater
		/// </summary>
		public int PageSize {
			get{ return pageSize;}
			set{ pageSize = value; }
		}

		public bool PageOnPostBackOnly
		{
			get{ return pageOnPostBackOnly;}
			set{ pageOnPostBackOnly = value; }
		}

		string applicationKey = null;
		public string ApplicationKey 
		{
			get
			{
				return applicationKey;
			}
			set
			{
				applicationKey = value;
			}
		}

        private bool _enablePager = true;
        public bool EnablePaging
        {
            get
            {
                //this.EnsureChildControls();
                //return postPager.Enabled;
                return _enablePager;
            }
            set
            {
                //this.EnsureChildControls();
                //postPager.Enabled = value;
                _enablePager = value;
            }
        }

        private BlogMirrorDisplayType _MirrorDisplayType = BlogMirrorDisplayType.AllBlogs;
        public BlogMirrorDisplayType MirrorDisplayType
        {
            get
            {
                return _MirrorDisplayType;
            }
            set
            {
                _MirrorDisplayType = value;
            }
        }

        public bool IncludeCategories
        {
            get{return includeCategories;}
            set{includeCategories = value;}
        }

        public bool ScorePosts
        {
            get{return scorePosts;}
            set{scorePosts = value;}
        }

		public bool IncludeAutodiscovery
		{
			get { return includeAutodiscovery; }
			set { includeAutodiscovery = value; }
		}

        ///<Summary>
        ///turns on or off the digg like comment boxes
        ///</Summary>
        bool showCommentCount = true;
        public bool ShowCommentCount
        {
            get { return showCommentCount; }
            set { showCommentCount = value; }
        }
	    
	    private int _groupID = -2;
		public int GroupID
		{
			get
			{
				if (_groupID == -2)
					_groupID = Globals.SafeInt(Context.Request.QueryString["GroupID"],-1);

				return _groupID;
			}
			set
			{
				_groupID = value;
			}
		}

        private int _sectionID = -2;
        public int SectionID
        {
            get
            {
                if (_sectionID == -2)
                    _sectionID = Globals.SafeInt(Context.Request.QueryString["SectionID"], -1);

                return _sectionID;
            }
            set
            {
                _sectionID = value;
            }
        }

        /// <summary>
        /// Property to control how threads are sorted for various views
        /// </summary>
        public BlogThreadSortBy SortBy {
            get { return sortBy; }
            set { sortBy = value; }
        }

	    protected override void AttachChildControls()
	    {
	        posts = FindControl("Posts") as AggregateList;
            title = FindControl("title") as Literal;

        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.EnsureChildControls();

        	CSContext cntx = CSContext.Current;
			WeblogConfiguration config = WeblogConfiguration.Instance();

            if (posts != null)
                posts.ShowCommentCount = this.ShowCommentCount;
			
            if(this.EnableTitle)
            {
                if(GroupID > -1)
                {
                    Group g = WeblogGroups.GetWeblogGroup(GroupID,true,false,false);
					if (g != null)
					{
						Head.AddSiteNameTitle(g.Name, Context);

						if (WeblogGroups.IsPublic(GroupID))
							UsersOnline.SetLocation(g.Name, cntx.RawUrl);
						else
							UsersOnline.PrivateLocation();
					}
                }
                else
                {
                    Head.AddSiteNameTitle("Blogs", Context);
                    UsersOnline.SetLocation("Viewing Blogs", cntx.RawUrl);
                }
            }

			string titleText = "";
			if(GroupID > -1)
			{
				Group g = WeblogGroups.GetWeblogGroup(GroupID,true,false,false);
				if (g != null)
					titleText = string.Format( ResourceManager.GetString("LatestPostsTo"), g.Name);
			}
			else
			{
				titleText = ResourceManager.GetString("LatestPosts");                
			}

			if (title != null)
			{
				title.Text = titleText;				
            }
            
			if (posts != null)
			{

				int day = Globals.SafeInt(Context.Request.QueryString["d"], -1);
				int month = Globals.SafeInt(Context.Request.QueryString["m"], -1);
				int year = Globals.SafeInt(Context.Request.QueryString["y"], -1 );

				BlogThreadQuery query =  BlogThreadQuery.CreateNewAggregateQuery();

				if(GroupID > -1)
				{
					query.GroupID = GroupID;
				}

                if (SectionID > -1)
                {
                    query.SectionID = SectionID;
                }

				if( month > 0 && month < 13 && day > 0 && day < 32 
					&& year > DateTime.MinValue.Year && year <= DateTime.MaxValue.Year )
				{
					try 
					{
						query.DateFilter = new DateTime( year, month, day );				
					}
					catch{}
				}

				query.BlogPostType = BlogPostType.Post;
			
				if (!Globals.IsNullorEmpty(this.ApplicationKey))
				{
					Weblog blog = Weblogs.GetWeblog(this.ApplicationKey);
					query.SectionID = blog.SectionID;
				}

				query.PageIndex = !pageOnPostBackOnly || Page.IsPostBack ? cntx.PageIndex : 0;
				query.PageSize = this.PageSize == -1 ? config.AggregatePostCount : this.PageSize;
				query.SortBy = sortBy;
				query.PostConfig = BlogPostConfig.IsCommunityAggregated | BlogPostConfig.IsAggregated;
                query.BlogMirrorDisplayType = MirrorDisplayType;

				if (config.HasAggregateTags)
				{
					query.Tags = config.DefaultAggregateTags;
					query.LogicallyOrTags = true;
				}

                if(this.ScorePosts && config.ScorePosts)
                {
                    ScoredPostList spl = WeblogPosts.GetScoredBlogThreads(query, true);
                    posts.TotalRecords = spl.TotalRecords;
                    posts.PageSize = spl.PageSize;
                    posts.DataSource = spl.Posts;
                    posts.PageIndex = spl.PageIndex;                    
                }
                else
                {
                    ThreadSet ts = WeblogPosts.GetBlogThreads(query, true, true);
                    posts.TotalRecords = ts.TotalRecords;
                    posts.PageSize = query.PageSize;
                    posts.DataSource = ts.Threads;
                    posts.PageIndex = query.PageIndex;
                }

				posts.EnablePaging = this.EnablePaging;
				posts.DataBind();

				if (this.IncludeAutodiscovery)
					Head.AddRssAutoDiscovery(titleText, BlogUrls.Instance().GroupRss(GroupID, this.MirrorDisplayType), this.Context);
			}
        }

    }
}
