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

using System;
using System.Collections;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Galleries.Components;

namespace CommunityServer.Galleries.Controls
{
    /// <summary>
    /// Summary description for EntryComments.
    /// </summary>
    public class EntryComments : GalleryThemedControl
    {

		#region Child Controls

        private Repeater Comments = null;
        private GalleryPost parent = null;
		private CommentForm Commentform1 = null;  

		#endregion
	
		#region Public Properties

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

		private GalleryPost commentFormDataSource;
		public GalleryPost CommentFormDataSource
		{
			get { return commentFormDataSource; }
			set { commentFormDataSource = value; }
		}


		#endregion

		#region Skin

        protected override void AttachChildControls()
        {
            Comments = FindControl( "Comments" ) as Repeater;
            if(Comments == null)
            {
                this.Controls.Clear();
                this.Visible = false;
                return;
            }

			

			Commentform1 = FindControl( "Commentform1" ) as CommentForm;

			Comments.ItemCreated +=new RepeaterItemEventHandler(Comments_ItemCreated);
            Comments.ItemCommand +=new RepeaterCommandEventHandler(Comments_ItemCommand);

        }

		#endregion

		#region Event Overrides

		protected override void OnLoad(System.EventArgs e)
		{
			base.OnLoad(e);
			if(!Page.IsPostBack)
				DataBind();
		}

		public override void DataBind()
		{
			base.DataBind();
			if(DataSource != null && Comments !=null)
			{
				DataSource.Organize();
				parent = DataSource.ThreadStarter as GalleryPost;

				Comments.DataSource = DataSource.Replies;
				Comments.DataBind();

			}
			BindData();

		}

		#endregion
		
		private void BindData()
    	{
			if(Commentform1 != null && CommentFormDataSource != null)
			{
				Commentform1.DataSource = CommentFormDataSource;
				Commentform1.DataBind();
			}
		}

	
		const string anchortag = "<a name=\"{0}\"></a>";
        private string Anchor(int ID)
        {
            return string.Format(anchortag,ID);
        }

        private int _anonymousUserID = -1;
        private bool IsAnonymousUserID(int userID)
        {
            if(_anonymousUserID == -1)
                _anonymousUserID = Users.GetAnonymousUser(true).UserID;


                return _anonymousUserID == userID;
        }

       

        private void Comments_ItemCreated(object sender, RepeaterItemEventArgs e)
        {
            if(parent == null)
                return;

            if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
            	GalleryPost entry = e.Item.DataItem as GalleryPost;
				if(entry != null)
				{
					Literal title = (Literal)(e.Item.FindControl("Title"));
					if(title != null)
					{
						// we should probably change skin format to dynamically wire up to 
						// skin located title and permalinks at some point
						title.Text = String.Format("{0}{1}", entry.Subject, Anchor(entry.PostID));
					}

					HyperLink perma = (HyperLink)e.Item.FindControl("PermaLink");
                    if(perma != null)
                    {
                        perma.NavigateUrl = GalleryUrls.Instance().ViewPicture(CurrentGallery.ApplicationKey , GalleryPosts.GetPicture(entry.ParentID));
                    }

					UserAvatar avatar = e.Item.FindControl("Avatar") as UserAvatar;
					if (avatar != null)
					{
						if(IsAnonymousUserID(entry.AuthorID) && !avatar.ShowAnonymousAvatar)
							avatar.Visible = false;
						else
							avatar.User = Users.GetUser(entry.AuthorID, false);
					}

					HyperLink namelink = (HyperLink)e.Item.FindControl("NameLink");
					if(namelink != null)
					{
						if(entry.HasTitleUrl)
						{
                            
							namelink.NavigateUrl = Globals.GetSiteUrls().Redirect(entry.TitleUrl);

							if(IsAnonymousUserID(entry.AuthorID))
								namelink.Attributes.Add("rel", "nofollow");
						}
						else
						{
							if(!IsAnonymousUserID(entry.AuthorID))
								namelink.NavigateUrl = Globals.GetSiteUrls().UserProfile(entry.AuthorID);
						}

						namelink.Text = entry.DisplayName;
						
						if(entry.GalleryPostType == GalleryPostType.Comment)
						{
							//NOTE: Should this be the true username...we use it to allow users to know if the user is real or anonymous?
							namelink.ToolTip = namelink.Text;
						}
						else if(entry.GalleryPostType == GalleryPostType.Trackback)
						{
							namelink.Attributes.Add("title", "TrackBack");
						}

					}

					Literal PostDate = (Literal)(e.Item.FindControl("PostDate"));
					if(PostDate != null)
					{
						PostDate.Text = entry.PostDate.ToString(ThemeConfig.DateFormat);
					}

					Literal Post = (Literal)(e.Item.FindControl("PostText"));
					if(Post != null)
					{
						Post.Text = entry.RenderedBody(PostTarget.Web);
					}
                   
                    
					LinkButton editlink = e.Item.FindControl("EditLink") as LinkButton;
					if(editlink != null)
					{
						if(Permissions.ValidatePermissions(this.CurrentGallery,Permission.Moderate, this.CurrentUser ))
						{
							editlink.Text = ResourceManager.GetString("CommentListing_Delete", "FileGallery.xml");
							editlink.CommandName = entry.PostID.ToString();
							editlink.Attributes.Add("onclick","return confirm(\"Are you sure you want to delete this comment?\");");
							editlink.Visible = true;
							editlink.CommandArgument = entry.PostID.ToString();
						}
						else
						{
							editlink.Visible = false;
						}
                    
					}
				}
            }
        }

        private void Comments_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            

            int entryID = Int32.Parse(e.CommandArgument as string);
            //WeblogPosts.Delete(CurrentGallery.SectionID, entryID, GalleryPostType.Comment, CSContext.Current.User.UserID);
			GalleryPosts.DeleteComment(entryID);

            //Need to do this a bit cleaner. 
            if(this.DataSource != null)
            {
            	ArrayList items = DataSource.Replies;
                for(int i = 0; i< items.Count; i++)
                {
                    if((items[i] as GalleryPost).PostID == entryID)
                    {
                        items.RemoveAt(i);
                        break;
                    }
                }

                this.Comments.DataSource = items;
                this.Comments.DataBind();
            }
        }
    }
}
