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

using System;
using System.Diagnostics;
using System.Reflection;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Blogs.Components;
using CommunityServer.Controls;

namespace CommunityServer.Blogs.Controls
{
	/// <summary>
	/// Summary description for EntryList.
	/// </summary>
	public class EntryList :  WeblogThemedControl
	{
        private Repeater entryItems = null;
        private IPagedControl listPager = null;

		public EntryList()
		{
            
		}

        public override void DataBind()
        {
            
            base.DataBind ();
            if(DataSource != null)
            {
                entryItems.DataSource = DataSource;
                entryItems.DataBind();

                if(listPager != null)
                {
                    listPager.Visible = EnablePaging;

                    if(EnablePaging)
                    {
                        listPager.TotalRecords = this.TotalRecords;
                        listPager.PageIndex = this.PageIndex;
                        listPager.PageSize = this.PageSize;
                    }
                }
                
            }
        }

        private int _totalRecords;
        /// <summary>
        /// Property TotalRecords (int)
        /// </summary>
        public int TotalRecords
        {
            get {  return this._totalRecords; }
            set {  this._totalRecords = value; }
        }

        private int _pageIndex;
        /// <summary>
        /// Property PageIndex (int)
        /// </summary>
        public int PageIndex
        {
            get {  return this._pageIndex; }
            set {  this._pageIndex = 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 15;
            }
            set 
            {
                ViewState[ "PageSize" ] = value;
            }
        }

        private object _dataSource;
        /// <summary>
        /// Property DataSource (object)
        /// </summary>
        public object DataSource
        {
            get {  return this._dataSource; }
            set {  this._dataSource = value; }
        }

		private bool _DisplayExcerpts;

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


	    protected override void AttachChildControls()
	    {
            entryItems = FindControl( "EntryItems" ) as Repeater;
            listPager = FindControl( "pager" ) as IPagedControl;

            if(entryItems != null)
            {
                entryItems.ItemCreated += new RepeaterItemEventHandler(entryItems_ItemDataBound);
            }
            
	    }

        private void entryItems_ItemDataBound(object sender, RepeaterItemEventArgs e) 
        {
            if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
            {
                WeblogPost entry = e.Item.DataItem as WeblogPost;
                if(entry != null) 
                {
                    PopulateWeblogPost(entry, e);
                }
                else
                {
                    IndexPost ip = e.Item.DataItem as IndexPost;
                    PopulateIndexPost(ip,e);
                }
            }
        }

        #region PopulateWeblogPost
        /// <summary>
        /// Binds a WeblogPost to the repeater
        /// </summary>
        /// <param name="entry"></param>
        /// <param name="e"></param>
        private void PopulateWeblogPost(WeblogPost entry, RepeaterItemEventArgs e)
	    {
	        HyperLink link = e.Item.FindControl("PermaLink") as HyperLink;
	        if(link != null) 
	        {
	            link.Text = entry.UserTime.ToString(ThemeConfig.DateFormat);
	            link.NavigateUrl = BlogUrls.Instance().Post(entry,CurrentWeblog);
	        }                    
    
	        link = e.Item.FindControl("postTitle") as HyperLink;
	        if(link != null) 
	        {
                if(entry.IsExternal)
                    link.NavigateUrl = entry.TitleUrl;
                else
	                link.NavigateUrl = BlogUrls.Instance().Post(entry,CurrentWeblog);

	            link.Text = entry.Subject;
	        }
    
	        IText Body = TextControlHelper.Create(e.Item.FindControl( "Body" ));
	        HyperLink readMore = e.Item.FindControl("ReadMoreLink") as HyperLink;
	        if(Body != null)
	        {
	            if((DisplayExcerpts || entry.BlogPostType == BlogPostType.Article) ||  entry.DisplayExcerpt)
	            {
	                if(entry.HasExcerpt)
	                    Body.Text = entry.Excerpt;
	                else if (entry.IsExternal)
                        Body.Text = entry.RenderedBody(PostTarget.Web);
                    else
	                    Body.Text = Formatter.RemoveHtml(entry.RenderedBody(PostTarget.Web),entry.ExcerptSize);

							
	                if(readMore != null)
	                {
                        if(entry.IsExternal)
                        {
                            readMore.Visible = false;
                        }
                        else
                        {
                            readMore.Visible = true;
                            readMore.Text = ResourceManager.GetString("Weblog_EntryList_ReadMore");
                            readMore.NavigateUrl = BlogUrls.Instance().Post(entry,CurrentWeblog);
                        }
	                    
	                }
	            }
	            else
	            {
	                if(readMore != null)
	                    readMore.Visible = false;

	                Body.Text = entry.RenderedBody(PostTarget.Web);
	            }
	        }
    
	        ResourceControl commentDesc = e.Item.FindControl("CommentDesc") as ResourceControl;
	        if(commentDesc != null)
	            commentDesc.Visible = false;
    
	        link = e.Item.FindControl( "CommentsLink" ) as HyperLink;
    
	        if(link != null) 
	        {
						
	            if((CurrentWeblog.EnableCommentsDefault && !entry.IsLocked) || entry.Replies > 0)
	            {
	                link.Text = string.Format(ResourceManager.GetString("Weblog_EntryList_Comments"),entry.Replies);
	                link.NavigateUrl = BlogUrls.Instance().Post(entry,CurrentWeblog) + "#comments";
	            }
	            else
	            {
	                link.Text = ResourceManager.GetString("Weblog_EntryList_CommentsOff");
	            }
	        }
    
    
	        link = e.Item.FindControl("EditLink") as HyperLink;
	        if(link != null)
	        {
	            if(Permissions.ValidatePermissions(CurrentWeblog,Permission.Post,CurrentUser))
	            {
	                link.Visible = true;
	                link.NavigateUrl = BlogUrls.Instance().PostEditor(CurrentWeblog.SectionID,entry.PostID);
	                link.Text = string.Format("[{0}]",ResourceManager.GetString("Edit"));
	                link.ToolTip = ResourceManager.GetString("Weblog_EntryList_Edit");
	            }
	            else
	                link.Visible = false;
	        }
    
	        BlogRatePost rib = e.Item.FindControl("Ratings") as BlogRatePost;
	        if(rib != null)
	        {
	            if(CurrentWeblog.ValidateRatings(entry))
	            {
	                rib.Visible = true;
	                rib.CurrentRating  = entry.RatingAverage;
	                rib.CurrentVotes = entry.TotalRatings;
	                rib.IsReadOnly = true;
	            }
	            else
	            {
	                rib.Visible = false;
	            }
	        }
    
	        link = e.Item.FindControl("AuthorLink") as HyperLink;
	        if(link != null)
	        {
				link.Text = entry.DisplayName;

				if (!Globals.IsNullorEmpty(entry.SubmittedUserName))
                {
                    link.NavigateUrl = entry.GetExtendedAttribute("channel_link");
                    link.Target = "new";

                    ResourceControl rc = e.Item.FindControl("PostByResource") as ResourceControl;
                    if(rc != null)
                        rc.ResourceName = "Weblog_Aggregate_From";
                }
                else
                {
                    link.NavigateUrl = Globals.GetSiteUrls().UserProfile(entry.AuthorID);
                }
	            
	        }
    
	        CategoryTagControl tags = e.Item.FindControl("Tags") as CategoryTagControl;
	        if(tags != null)
	        {
	            tags.DataSource = WeblogPosts.GetCategoryTags(entry);
	            tags.DataBind();
	        }
    
	        DownloadAttachmentLink attachment = e.Item.FindControl("Attachment") as DownloadAttachmentLink;
	        if(attachment != null && entry.HasAttachment)
	        {
	            attachment.DataSource = entry.Attachment;
	            attachment.DataBind();
	        }

            Literal CommentSeperator = e.Item.FindControl("CommentSeperator") as Literal;
            if(CommentSeperator != null)
                CommentSeperator.Text = ThemeConfig.Seperator;

			InlineTagEditorPanel inlineTagEditor = e.Item.FindControl("InlineTagEditorPanel") as InlineTagEditorPanel;
			if (inlineTagEditor != null)
			{
				inlineTagEditor.PostID = entry.PostID;
				inlineTagEditor.SelectedTags = entry.Categories;
			}

	    }

        #endregion

        #region PopulateIndexPost

        /// <summary>
        /// Handles processing the special post object returned during searches
        /// </summary>
        /// <param name="entry"></param>
        /// <param name="e"></param>
        private void PopulateIndexPost(IndexPost entry, RepeaterItemEventArgs e)
        {
			WeblogPost weblogPost = null;

			CategoryTagControl tags = e.Item.FindControl("Tags") as CategoryTagControl;
			HyperLink  commentslink = e.Item.FindControl( "CommentsLink" ) as HyperLink;
			BlogRatePost rib = e.Item.FindControl("Ratings") as BlogRatePost;
			DownloadAttachmentLink attachment = e.Item.FindControl("Attachment") as DownloadAttachmentLink;
			IText Body = TextControlHelper.Create(e.Item.FindControl( "Body" ));

			if (tags != null || commentslink != null || rib != null || attachment != null || Body != null)
			{
				weblogPost = WeblogPosts.GetPost(entry.PostID, true, true, true);
				if (weblogPost == null)
					return;
			}

            HyperLink link = e.Item.FindControl("PermaLink") as HyperLink;
            if(link != null) 
            {
                link.Text = entry.PostDate.ToString(ThemeConfig.DateFormat);
                link.NavigateUrl = entry.Url;
            }                    
    
            link = e.Item.FindControl("postTitle") as HyperLink;
            if(link != null) 
            {
                if(weblogPost != null && !Globals.IsNullorEmpty(weblogPost.TitleUrl))
                {
                    link.NavigateUrl = weblogPost.TitleUrl;
                }
                else
                {
                    link.NavigateUrl = entry.Url;
                }
                link.Text = entry.Title;
            }
    
            HyperLink readMore = e.Item.FindControl("ReadMoreLink") as HyperLink;
            if(Body != null)
            {
				if(weblogPost.HasExcerpt)
					Body.Text = weblogPost.Excerpt;
				else
					Body.Text = Formatter.RemoveHtml(weblogPost.RenderedBody(PostTarget.Web),250);
						
				if(readMore != null)
				{
					readMore.Visible = true;
					readMore.NavigateUrl = BlogUrls.Instance().Post(weblogPost,CurrentWeblog);
					readMore.Text = ResourceManager.GetString("Weblog_EntryList_ReadMore");
				}
            }
    
            ResourceControl commentDesc = e.Item.FindControl("CommentDesc") as ResourceControl;
            if(commentDesc != null)
                commentDesc.Visible = false;
    
    
            if(commentslink != null) 
            {
				if (weblogPost != null)
				{
					if((CurrentWeblog.EnableCommentsDefault && !weblogPost.IsLocked) || weblogPost.Replies > 0)
					{
						commentslink.Text = string.Format(ResourceManager.GetString("Weblog_EntryList_Comments"),weblogPost.Replies);
						commentslink.NavigateUrl = BlogUrls.Instance().Post(weblogPost,CurrentWeblog) + "#comments";
					}
					else
					{
						commentslink.Text = ResourceManager.GetString("Weblog_EntryList_CommentsOff");
					}
				}
				else
					commentslink.Visible = false;
            }
    
    
            link = e.Item.FindControl("EditLink") as HyperLink;
            if(link != null)
            {
                if(Permissions.ValidatePermissions(CurrentWeblog,Permission.Post,CurrentUser))
                {
                    link.Visible = true;
                    link.NavigateUrl = BlogUrls.Instance().PostEditor(CurrentWeblog.SectionID,entry.PostID);
                    link.Text = string.Format("[{0}]",ResourceManager.GetString("Edit"));
                    link.ToolTip = ResourceManager.GetString("Weblog_EntryList_Edit");
                }
                else
                    link.Visible = false;
            }
    
           
            if(rib != null)
            {
				if (weblogPost != null)
				{
					if(CurrentWeblog.ValidateRatings(weblogPost))
					{
						rib.Visible = true;
						rib.CurrentRating  = weblogPost.RatingAverage;
						rib.CurrentVotes = weblogPost.TotalRatings;
						rib.IsReadOnly = true;
					}
					else
					{
						rib.Visible = false;
					}
				}
				else
					rib.Visible = false;
            }
    
            link = e.Item.FindControl("AuthorLink") as HyperLink;
            if(link != null)
            {
                if(weblogPost != null)
                {
                    link.Text = weblogPost.DisplayName;
                    link.NavigateUrl = weblogPost.GetExtendedAttribute("channel_link");

                    ResourceControl rc = e.Item.FindControl("PostByResource") as ResourceControl;
                    if(rc != null)
                        rc.ResourceName = "Weblog_Aggregate_From";
                }
                else
                {
                    link.Text = Users.GetUser(0, entry.UserName, false, false).DisplayName;
                    link.NavigateUrl = Globals.GetSiteUrls().UserProfile(entry.UserName);
                }
            }
    
            
			if(tags != null)
			{
				if (weblogPost != null)
				{
					tags.DataSource = WeblogPosts.GetCategoryTags(weblogPost);
					tags.DataBind();
				}
				else
					tags.Visible = false;
			}
    
            
            if(attachment != null)
            {
				if (weblogPost != null && weblogPost.HasAttachment)
				{
					attachment.DataSource = weblogPost.Attachment;
					attachment.DataBind();
				}
				else
					attachment.Visible = false;
            }

			InlineTagEditorPanel inlineTagEditor = e.Item.FindControl("InlineTagEditorPanel") as InlineTagEditorPanel;
			if (inlineTagEditor != null)
				inlineTagEditor.Visible = false;
        }

        #endregion
	}
}
