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

using System;
using System.Web.UI.WebControls;
using CommunityServer;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Files.Components;
using System.Web.UI;

namespace CommunityServer.Files.Controls
{

	public class CommentListing : FileGalleryTemplatedWebControl
	{
		CSContext csContext = CSContext.Current;

		#region Child Controls

		private Repeater Comments;

		private TextBox CommentName;
		private TextBox CommentWebsite;
		private TextBox CommentBody;
		private IButton CommentSubmit;

		#endregion

		#region Skin

		protected override void AttachChildControls()
		{
			Comments = (Repeater)FindControl( "Comments" );

			CommentName = (TextBox)FindControl( "CommentName" );
			CommentWebsite = (TextBox)FindControl( "CommentWebsite" );
			CommentBody = (TextBox)FindControl( "CommentBody" );
			CommentSubmit = FindButton( "CommentSubmit" );

			InitializeChildControls();
		}

		private void InitializeChildControls()
		{
			if (Comments != null)
			{
				Comments.ItemDataBound += new RepeaterItemEventHandler(Comments_ItemDataBound);
				Comments.ItemCommand += new RepeaterCommandEventHandler(Comments_ItemCommand);
			}

			if (CommentSubmit != null)
				CommentSubmit.Click += new EventHandler(CommentSubmit_Click);
		}

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

			if (!CurrentFolder.EnableComments)
			{
				this.Visible = false;
				return;
			}

			DataBind();
		}

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

			// Check if comments are enabled
			this.Visible = CurrentEntry.EnableComments;

			// Check if anonymous comments are allowed and if the current user is anonymous
			FileGalleryPermission permission = CurrentFolder.ResolvePermission( csContext.User ) as FileGalleryPermission;
			if(CurrentEntry.IsLocked || !permission.Reply)
				FindControl( "AddCommentArea" ).Visible = false;

			// Add some resource labels
			CommentSubmit.Text = FileGalleryResourceManager.GetString( "Add" );

			if(CurrentFolder.ModerateComments)
				CommentSubmit.Attributes.Add("onclick", "alert('" + FileGalleryResourceManager.GetString("CommentListing_ModerationAlert").Replace("'", "\'") + "');" );

			BindComments();
		}

		private void BindComments()
		{
			bool allowUnapproved = false;
			User user = csContext.User;

			if(user.IsFileAdministrator || Permissions.ValidatePermissions( CurrentFolder, Permission.Moderate, user ))
				allowUnapproved = true;

			Comments.DataSource = EntryComments.GetComments(CurrentEntry.PostID, allowUnapproved);
			Comments.DataBind();

			Control anonymousUserArea = FindControl( "AnonymousUser" );
			if (anonymousUserArea != null)
				anonymousUserArea.Visible = user.IsAnonymous;

			Control registeredUserArea = FindControl( "RegisteredUser" );
			if (registeredUserArea != null)
				registeredUserArea.Visible = !user.IsAnonymous;
			
			IText userName = FindText("UserName");
			if (userName != null)
				userName.Text = csContext.User.DisplayName;
			
		}

		private void Comments_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			EntryComment dataItem = e.Item.DataItem as EntryComment;

			switch( e.Item.ItemType ) 
			{
				case ListItemType.Item:
				case ListItemType.AlternatingItem:

					PlaceHolder Who = (PlaceHolder)e.Item.FindControl( "ComWho" );
					IText Date = TextControlHelper.Create(e.Item.FindControl( "ComDate" ));
					IText Text = TextControlHelper.Create(e.Item.FindControl( "ComBody" ));
					IButton Approve = ButtonManager.Create(e.Item.FindControl( "ApproveButton" ));
					IButton Delete = ButtonManager.Create(e.Item.FindControl( "DeleteButton" ));
					UserAvatar avatar = e.Item.FindControl("Avatar") as UserAvatar;
					
					if (avatar != null)
					{
						if(dataItem.User.IsAnonymous && !avatar.ShowAnonymousAvatar)
							avatar.Visible = false;
						else
							avatar.User = dataItem.User;
					}

					// Date added
					User user = csContext.User;

					if (Date != null)
					{
						if(!user.IsAnonymous)
							Date.Text = dataItem.PostDate.ToString(user.Profile.DateFormat);
						else
							Date.Text = dataItem.PostDate.ToString(csContext.SiteSettings.DateFormat);
					
						Date.Text += " " + dataItem.PostDate.ToString(csContext.SiteSettings.TimeFormat);
					}

					if (Text != null)
						Text.Text = dataItem.RenderedBody(PostTarget.Web);

					// Configure the link to approve the post
					if (Approve != null)
					{
						if(!dataItem.IsApproved)
						{
							Approve.Visible = true;
							Approve.Text = FileGalleryResourceManager.GetString( "CommentListing_Approve" );
							Approve.CommandName = "ApproveComment";
							Approve.CommandArgument = dataItem.PostID.ToString();
						}
						else
							Approve.Visible = false;
					}

					// Configure the link to remove comments
					if (Delete != null)
					{
						if(csContext.User.IsFileAdministrator || Permissions.ValidatePermissions( CurrentFolder, Permission.Moderate | Permission.Delete, csContext.User ))
						{
							Delete.Visible = true;
							Delete.Text = FileGalleryResourceManager.GetString( "CommentListing_Delete" );
							Delete.CommandName = "DeleteComment";
							Delete.CommandArgument = dataItem.PostID.ToString();
						}
						else
							Delete.Visible = false;
					}

					if(dataItem.HasTitleUrl)
					{
						HyperLink WebsiteName = new HyperLink();
						WebsiteName.Text = dataItem.DisplayName;
						WebsiteName.NavigateUrl = dataItem.TitleUrl;
                        WebsiteName.Attributes.Add("rel", "nofollow");
						Who.Controls.Add( WebsiteName );
					}
					else if(!dataItem.User.IsAnonymous)
					{
						// Was a logged in user
						HyperLink UserLink = new HyperLink();
						UserLink.Text = dataItem.User.DisplayName;
						UserLink.NavigateUrl = Globals.GetSiteUrls().UserProfile(dataItem.User.UserID);
						Who.Controls.Add( UserLink );
					}
					else
					{
						Label Name = new Label();
						Name.Text = dataItem.SubmittedUserName;
						Who.Controls.Add( Name );
					}

					break;
			}
		}

		private void CommentSubmit_Click(object sender, EventArgs e)
		{
			EntryComment comment = new EntryComment();

			// Make sure the comment body isn't blank
			if(CommentBody.Text.Trim() == string.Empty)
			{
				FindControl( "CommentBodyErrMsg" ).Visible = true;
				Page.RegisterClientScriptBlock( "commentError", "<script language='JavaScript'>alert('Please include some content in the comment body');</script>" );
				return;
			}

			// Apply all of the settings
			comment.User = csContext.User;
			comment.Username = comment.User.Username;
			comment.Body = CommentBody.Text;
			comment.UserHostAddress = Page.Request.UserHostAddress;

			// See if posts are moderated
			if(CurrentFolder.ModerateComments)
			{
				if(Permissions.ValidatePermissions( CurrentFolder, Permission.Moderate, comment.User ))
					comment.IsApproved = true;
				else
					comment.IsApproved = false;
			}
			else
				comment.IsApproved = true;

			// Put "Anonymous" in the name if the user is anonymous and they don't give a name
			if(csContext.User.IsAnonymous && (CommentName.Text.Trim() == string.Empty))
				comment.SubmittedUserName = comment.User.DisplayName;
			else
				comment.SubmittedUserName = CommentName.Text;

			// Add check for http:// in the website URL
			CommentWebsite.Text = CommentWebsite.Text.Trim();
			if(CommentWebsite.Text.StartsWith("http://") || CommentWebsite.Text.StartsWith("https://"))
				comment.TitleUrl = CommentWebsite.Text;
			else if (CommentWebsite.Text.Length > 0)
				comment.TitleUrl =  "http://" + CommentWebsite.Text;
			else
				comment.TitleUrl = String.Empty;

			// Send to the database
			comment = EntryComments.CreateComment(CurrentEntry.PostID, comment);

			// Email the user
			//HiveEmails.NewComment(CurrentFolder.ApplicationKey, CategoryID, PictureID, comment);

			// Redirect to the page so user's can hit refresh and have the post show up twice
			Context.Response.Redirect( FileGalleryUrls.Instance().ViewEntry(CurrentFolder.ApplicationKey, CurrentEntry.PostID) );
		}

		private void Comments_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			switch(e.CommandName)
			{
				case "ApproveComment":
					EntryComments.ApproveComment(int.Parse((string)e.CommandArgument), CurrentEntry.PostID);
					DataBind();
					break;
				case "DeleteComment":
					EntryComments.DeleteComment(int.Parse((string)e.CommandArgument), CurrentEntry.PostID);
					DataBind();
					break;
			}
		}
	}
}
