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

using System;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using CommunityServer.Blogs.Components;
using CommunityServer.Components;
using CommunityServer.Controls;

using System.Collections;

namespace CommunityServer.Blogs.Controls
{
    /// <summary>
    /// Summary description for EntryListContainer.
    /// </summary>
    public class EntryListContainer : WeblogThemedControl
    {
		CSContext csContext = CSContext.Current;

        #region ChildControls
        private EntryList entryItems = null;
        private IText listTitle = null;

        //private Pager listPager = null;
        private HtmlGenericControl titleWrapper = null;
        #endregion

        public EntryListContainer()
        {
			
        }

        #region Public Properties

		public virtual string Tags
		{
			get
			{
				return String.Join(",", FilterTags);
			}
			set
			{
				ArrayList tags = new ArrayList();
				foreach (string tag in value.Split(','))
				{
					if (!Globals.IsNullorEmpty(tag.Trim()))
						tags.Add(tag.Trim());
				}
				FilterTags = (string[]) tags.ToArray(typeof(string));
			}
		}

		public virtual bool LogicallyOrTags
		{
			get
			{
				Object state = ViewState["LogicallyOrTags"];
				if ( state != null ) 
				{
					return (Boolean)state;
				}
				return false;
			}
			set
			{
				ViewState["LogicallyOrTags"] = value;
			}
		}

		string[] _filterTags = null;
		public string[] FilterTags
		{
			get
			{
				if (_filterTags == null)
					return csContext.Tags;
				else
					return _filterTags;
			}
			set
			{
				_filterTags = value;
			}
		}

        /// <summary>
        /// Gets or sets the type of thread to display
        /// </summary>
        [
        System.ComponentModel.DefaultValue( BlogThreadType.Recent ),
        ]
        public virtual BlogThreadType BlogThreadType 
        {
            get 
            {
                Object state = ViewState["BlogThreadType"];
                if ( state != null ) 
                {
                    return (BlogThreadType)state;
                }
                return BlogThreadType.Recent;
            }
            set 
            {
                ViewState["BlogThreadType"] = value;
            }
        }

        /// <summary>
        /// Gets or sets the sort order of the displayed posts.
        /// </summary>
        [
        System.ComponentModel.DefaultValue( BlogThreadSortBy.MostRecent ),
        ]
        public virtual BlogThreadSortBy BlogThreadSortBy 
        {
            get 
            {
                Object state = ViewState["BlogThreadSortBy"];
                if ( state != null ) 
                {
                    return (BlogThreadSortBy)state;
                }
                return BlogThreadSortBy.MostRecent;
            }
            set 
            {
                ViewState["BlogThreadSortBy"] = value;
            }
        }

        /// <summary>
        /// Gets or sets the type of posts to display.
        /// </summary>
        [
        System.ComponentModel.DefaultValue( BlogPostType.Post ),
        ]
        public virtual BlogPostType BlogPostType 
        {
            get 
            {
                Object state = ViewState["BlogPostType"];
                if ( state != null ) 
                {
                    return (BlogPostType)state;
                }
                return BlogPostType.Post;
            }
            set 
            {
                ViewState["BlogPostType"] = value;
            }
        }

        /// <summary>
        /// Gets or sets if the results are paged.
        /// </summary>
        [
        System.ComponentModel.DefaultValue( false ),
        ]
        public virtual Boolean EnablePaging 
        {
            get 
            {
                Object state = ViewState["EnablePaging"];
                if ( state != null ) 
                {
                    return (Boolean)state;
                }
                return false;
            }
            set 
            {
                ViewState["EnablePaging"] = value;
            }
        }

        /// <summary>
        /// Gets or sets the size of a page when paging is enabled.
        /// </summary>
        [
        System.ComponentModel.DefaultValue( 15 ),
        ]
        public virtual Int32 PageSize 
        {
            get 
            {
                Object state = ViewState[ "PageSize" ];
                if ( state != null ) 
                {
                    return (Int32)state;
                }
                return WeblogConfiguration.Instance().IndividualPostCount;
            }
            set 
            {
                ViewState[ "PageSize" ] = value;
            }
        }

        /// <summary>
        /// Gets or sets the direction of the sort.
        /// </summary>
        [
        System.ComponentModel.DefaultValue( SortOrder.Descending ),
        ]
        public virtual SortOrder SortOrder 
        {
            get 
            {
                Object state = ViewState["SortOrder"];
                if ( state != null ) 
                {
                    return (SortOrder)state;
                }
                return SortOrder.Descending;
            }
            set 
            {
                ViewState["SortOrder"] = value;
            }
        }

		
		private bool _DisplayExcerpts;

		public bool DisplayExcerpts
		{
			get{return _DisplayExcerpts;}
			set{_DisplayExcerpts = value;}
		}

        #endregion

        #region Wire up Skin
        protected override void AttachChildControls()
        {
            entryItems = FindControl( "postlist" ) as EntryList;
            if(entryItems != null)
            {
                entryItems.DisplayExcerpts = this.DisplayExcerpts;
                entryItems.EnablePaging = this.EnablePaging;
            }

            listTitle = FindText( "listTitle" );
            titleWrapper = FindControl( "titleWrapper" ) as HtmlGenericControl;
            
        }
        #endregion

        #region Data

        public override void DataBind() 
        {
            base.DataBind();

            BlogThreadQuery query = Query();
            query.IncludeCategories = true;
            ThreadSet ts = WeblogPosts.GetBlogThreads(query,true);
            
            entryItems.DataSource = ts.Threads;
            entryItems.TotalRecords = ts.TotalRecords;
            entryItems.PageSize = PageSize;
            entryItems.PageIndex = query.PageIndex;

             entryItems.DataBind();

            //this.listPager.Visible = this.EnablePaging && this.PageSize != 0;


            switch(query.BlogThreadType)
            {
                case BlogThreadType.Day:
                    listTitle.Text = query.DateFilter.ToLongDateString() + " - " + ResourceManager.GetString("Weblog_EntryList_Posts");
                    break;
                case BlogThreadType.Month:
                    listTitle.Text = query.DateFilter.ToString("MMMM yyyy") + " - " + ResourceManager.GetString("Weblog_EntryList_Posts");
                    
                    break;
                default:
                    titleWrapper.Visible = false;
                    break;
            }

            if(!Globals.IsNullorEmpty(listTitle.Text))
            {
                this.SetPageTitle(listTitle.Text);                
            }
            else
            {
                this.SetPageTitle(string.Empty);
            }
            

        }

        protected BlogThreadQuery Query() 
        {
        	BlogThreadQuery query = BlogThreadQuery.CreateNewSingleBlogQuery(CurrentWeblog.SectionID);
			query.BlogPostType = BlogPostType.Post;
			query.BlogThreadType = this.BlogThreadType;
            query.SortOrder = SortOrder;
            query.PageIndex = csContext.PageIndex;
            query.PageSize = PageSize;

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

            //eventually should be able to view by date and category!
            switch(query.BlogThreadType) 
            {
                case BlogThreadType.Category:
                        query.CategoryID = csContext.CategoryID;
                        query.BlogPostType = BlogPostType.Post | BlogPostType.Article;
                    break;

                case BlogThreadType.Day:
                case BlogThreadType.Month:
                case BlogThreadType.Year:
                    query.DateFilter = GetDate();
					query.PageSize = int.MaxValue;

                    break;

				case BlogThreadType.Tags:
					query.BlogPostType = BlogPostType.Post | BlogPostType.Article;

					break;

				default:
					query.PostConfig = BlogPostConfig.IsAggregated;
					//query.FirstPageOnly = true;
					
					break;
            }


//			if ( this.EnablePaging && this.PageSize != 0 ) 
//			{
//				query.PageIndex = entryItems.PageIndex;
//				query.PageSize = PageSize;
//			}

            return query;
        }



        #endregion

        #region Events
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

                DataBind();

        }


        #endregion

        #region Helpers
        protected DateTime GetDate()
        {
            int year = Context.Request.QueryString["Y"] != null ? Int32.Parse(Context.Request.QueryString["Y"]) : 2000;
            int month = Context.Request.QueryString["M"] != null ? Int32.Parse(Context.Request.QueryString["M"]) : 2000;
            int day = Context.Request.QueryString["D"] != null ? Int32.Parse(Context.Request.QueryString["D"]) : 2000;
            return new DateTime(year,month,day);
        }
        #endregion

    }
}
