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

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

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

	
		Repeater posts = null;
		IPagedControl postPager = null;
		private WeblogConfiguration config = WeblogConfiguration.Instance();
        
        private int _totalRecords;
		/// <summary>
		/// Property TotalRecords (int)
		/// </summary>
		public int TotalRecords
		{
			get
			{
				return _totalRecords;
			}
			set
			{
				this._totalRecords = value;
			}
		}

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

        ///<Summary>
        ///Controls the amount of text to display in the title
        ///</Summary>
        int titleTextLength = -1;
        public int TitleTextLength {
            get { return titleTextLength; }
            set { titleTextLength = value; }
        }

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

		private bool _enablePager = true;
		public bool EnablePaging
		{
			get
			{
				//this.EnsureChildControls();
				//return postPager.Enabled;
				return _enablePager;
			}
			set
			{
				//this.EnsureChildControls();
				//postPager.Enabled = value;
				_enablePager = 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 object _dataSource;

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

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

                if(postPager != null)
                {
                    if(EnablePaging)
                    {
                        postPager.Visible = true;
                        postPager.PageSize = this.PageSize;
                        postPager.PageIndex = this.PageIndex;// + 1;
                        postPager.TotalRecords = this.TotalRecords;
                    }
                    else
                        postPager.Visible = false;
                }
			}
		}


		protected override void AttachChildControls()
		{
			posts = FindControl("Posts") as Repeater;
			postPager = FindControl("PostsPager") as IPagedControl;
			posts.ItemDataBound += new RepeaterItemEventHandler(posts_ItemDataBound);
		}



		private void posts_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
			{
				WeblogPost post = e.Item.DataItem as WeblogPost;
                if (post == null)
                    return;

                HtmlTableCell commentCountBox = e.Item.FindControl("CommentCountBox") as HtmlTableCell;

                if (commentCountBox != null)
                    commentCountBox.Visible = this.ShowCommentCount;

					HyperLink titleLink = e.Item.FindControl("TitleLink") as HyperLink;

                    // Shorten the title for display purposes, e.g. 'Community Ser...'
                    if (TitleTextLength > 0) {

                        titleLink.Text = Formatter.CheckStringLength(post.Subject, TitleTextLength);
                        titleLink.NavigateUrl = Globals.IsNullorEmpty(post.TitleUrl) ? BlogUrls.Instance().Post(post) : post.TitleUrl;
                        titleLink.ToolTip = post.Subject;
                    } else {
                        titleLink.Text = post.Subject;
                        titleLink.NavigateUrl = BlogUrls.Instance().Post(post);
                    }

					Literal body = e.Item.FindControl("Body") as Literal;
                    if (body != null) {
                        if (config.TruncateAggregatePost)
                        {
                            if(post.HasExcerpt)
                            {
                                body.Text = Formatter.RemoveHtml(post.Excerpt, config.AggregatePostSize) + "...";
                            }
                            else
                            {
                                body.Text = Formatter.RemoveHtml(post.RenderedBody(PostTarget.Web), config.AggregatePostSize) + "...";    
                            }
                            
                        }
                            
                        else
                            body.Text = post.RenderedBody(PostTarget.Web);
                    }

                    HyperLink User = e.Item.FindControl("User") as HyperLink;
                    if (User != null) {
                        if(post.IsExternal)
                        {
                            User.Text = post.SubmittedUserName;
                            User.NavigateUrl = post.GetExtendedAttribute("channel_link");
                            ResourceControl rc = e.Item.FindControl("PostByResource") as ResourceControl;
                            if(rc != null)
                                rc.ResourceName = "Weblog_Aggregate_From";
                        }
                        else
                        {
                            User.Text = post.DisplayName;
                            User.NavigateUrl = SiteUrls.Instance().UserProfile(post.AuthorID);
                        }
                    }

					HyperLink Blog = e.Item.FindControl("Blog") as HyperLink;
                    if (Blog != null) {
                        Blog.Text = post.Weblog.Name;
                        Blog.NavigateUrl = BlogUrls.Instance().HomePage(post.Section.ApplicationKey);
                    }

                    HyperLink Comments = e.Item.FindControl( "CommentsLink" ) as HyperLink;
                    if (Comments != null) {
                        Comments.NavigateUrl = BlogUrls.Instance().Post(post) + "#comments";
                        Comments.Text = String.Format(ResourceManager.GetString("Weblog_EntryList_Comments"), (!post.Weblog.EnableCommentsOverride || !post.Weblog.EnableCommentsDefault || post.IsLocked) ? "0" : post.Replies.ToString());
                    }

					HyperLink Comment = e.Item.FindControl( "Comment" ) as HyperLink;
					if (Comment != null) 
					{
						Comment.NavigateUrl = BlogUrls.Instance().Post(post) + "#comments";
						Comment.Text = ResourceManager.GetString("Weblog_EntryList_Comment");
					}

					HyperLink CommentCount = e.Item.FindControl( "CommentCount" ) as HyperLink;
					if (CommentCount != null) 
					{
						CommentCount.NavigateUrl = BlogUrls.Instance().Post(post) + "#comments";
						CommentCount.Text = (!post.Weblog.EnableCommentsOverride || !post.Weblog.EnableCommentsDefault || post.IsLocked) ? "0" : post.Replies.ToString();
					}

                    Literal Posted = e.Item.FindControl("Posted") as Literal;
                    if (Posted != null) {
                        Posted.Text = Formatter.FormatAgoDate(post.PostDate);
                    }

					HyperLink linkImage = e.Item.FindControl("linkImage") as HyperLink;
					if (linkImage != null)
					{
						linkImage.NavigateUrl = titleLink.NavigateUrl;
						linkImage.ToolTip = post.Subject;
					}

					UserAvatar avatar = e.Item.FindControl("Avatar") as UserAvatar;
					if (avatar != null) 
					{
						avatar.User = Users.GetUser(post.AuthorID, false);
					}

					BlogRatePost rib = e.Item.FindControl("Ratings") as BlogRatePost;
					if(rib != null)
					{
						rib.Visible = true;
						rib.CurrentRating = post.RatingAverage;
						rib.CurrentVotes = post.TotalRatings;
						rib.IsReadOnly = true;
					}

					HyperLink Views = e.Item.FindControl( "ViewsLink" ) as HyperLink;
					if (Views != null) 
					{
						Views.NavigateUrl = BlogUrls.Instance().Post(post);
						Views.Text = String.Format(ResourceManager.GetString("Weblog_EntryList_Views"), post.Views.ToString());
					}


					PlaceHolder tags = e.Item.FindControl("TagsList") as PlaceHolder;
					if (tags != null)
					{
						if (post.Categories != null && post.Categories.Length > 0)
						{
							tags.Controls.Add(new System.Web.UI.LiteralControl(ResourceManager.GetString("TagListTitle")));

							for (int i = 0; i < post.Categories.Length; i++)
							{
								string tag = post.Categories[i];

								if (i > 0)
									tags.Controls.Add(new System.Web.UI.LiteralControl(ResourceManager.GetString("TagListDelimiter")));

								HyperLink link = new HyperLink();
								link.NavigateUrl = SiteUrls.Instance().TagsBrowser(new string[] {tag});
								link.Text = tag;
								link.Attributes.Add("rel", "tag");
						
								tags.Controls.Add(link);
							}
						}
						else 
							tags.Visible = false;
					}
				
			}
		}
	}
}