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

using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Discussions.Components;

namespace CommunityServer.Discussions.Controls
{
	// *********************************************************************
	//  DeletePost
	//
	/// <summary>
	/// This control is used to delete posts
	/// </summary>
	// ***********************************************************************/
	public class DeletePost : TemplatedWebControl
	{
		#region Child Controls

		CSContext csContext;
		PostFlatPreview postPreview;
		Label deletedBy;
		YesNoRadioButtonList deleteChildren;
		Label deleteChildrenExplanation;
		RequiredFieldValidator deleteChildrenValidator;

		TemplateDropDownList reasonTemplate;
		TextBox reasonForDelete;
		RequiredFieldValidator reasonValidator;
		Button deleteButton;
		Button cancelButton;
		ForumPost postToDelete;
		string template = string.Empty;

		#endregion

		protected override void OnInit(EventArgs e)
		{
			csContext = CSContext.Current;

			if (SkinName == null)
				ExternalSkinFileName = "DeletePost.ascx";
			else
				ExternalSkinFileName = SkinName;

			// Get the post we are deleting
			postToDelete = Posts.GetPost(csContext.PostID, csContext.User.UserID);

			// Check if the user has permission to delete the post
			Permissions.AccessCheck(postToDelete.Section, Permission.Delete, csContext.User, postToDelete);

			base.OnInit(e);
		}

		#region Skin

		protected override void AttachChildControls()
		{
			// Displays the post to be deleted
			postPreview = (PostFlatPreview)FindControl("PostPreview");
			if (postPreview != null)
			{
				postPreview.DataSource = new object[] {postToDelete};
				postPreview.DataBind();
			}

			// Displays the user about to delete the post
			deletedBy = (Label)FindControl("DeletedBy");
			if (deletedBy != null)
				deletedBy.Text = csContext.User.Username;

			// Should children of deleted post be deleted (default is no)
			deleteChildren = (YesNoRadioButtonList)FindControl("DeleteChildren");
			if (deleteChildren != null)
			{
				deleteChildrenExplanation = (Label)FindControl("DeleteChildrenExplanation");

				if ((postToDelete.PostLevel > 1) && (postToDelete.Replies > 0))
				{
					deleteChildren.Enabled = true;
					deleteChildren.SelectedValue = false;

					// Explain options to delete/preserve children
					if (deleteChildrenExplanation != null)
						deleteChildrenExplanation.Text = ResourceManager.GetString("DeletePost_OptionDeleteChildren");
				}
				else if (postToDelete.PostLevel == 1)
				{
					deleteChildren.Enabled = false;
					deleteChildren.SelectedValue = true;

					// Explain why deletion of children will be forced (thread starter)
					if (deleteChildrenExplanation != null)
						deleteChildrenExplanation.Text = ResourceManager.GetString("DeletePost_ForceDeleteChildren");
				}
				else
				{
					deleteChildren.Enabled = false;
					deleteChildren.SelectedValue = false;

					// Explain why user has no option (no children)
					if (deleteChildrenExplanation != null)
						deleteChildrenExplanation.Text = ResourceManager.GetString("DeletePost_ForcePreserveChildren");
				}
			}

			// Require a selection regarding children
			deleteChildrenValidator = (RequiredFieldValidator)FindControl("DeleteChildrenValidator");
			if (deleteChildrenValidator != null)
				deleteChildrenValidator.ErrorMessage = ResourceManager.GetString("DeletePost_ValidateDeleteChildren");

			// Allows selection of templated reason for deletion
			reasonTemplate = (TemplateDropDownList)FindControl("ReasonTemplate");

			// Free form reason for deletion
			reasonForDelete = (TextBox)FindControl("DeleteReason");

			// Require a reason for deletion
			reasonValidator = (RequiredFieldValidator) FindControl("ValidateReason");
			if (reasonValidator != null)
				reasonValidator.ErrorMessage = ResourceManager.GetString("DeletePost_ValidateReason");

			// Button used to delete post (confirm client-side)
			deleteButton = (Button) FindControl("DeletePost");
			if (null != deleteButton) 
			{
				deleteButton.Attributes["onclick"] = "return confirm('" + ResourceManager.GetString("DeletePost_PopupConfirmation").Replace("'", @"\'") + "');";
				deleteButton.Text = ResourceManager.GetString("DeletePost_DeletePost");
			}

			// Button used to cancel deletion
			cancelButton = (Button) FindControl("CancelDelete");
			if (null != cancelButton) 
				cancelButton.Text = ResourceManager.GetString("DeletePost_CancelDelete");

			InitializeChildControls();
		}

		private void InitializeChildControls()
		{
			if (null != reasonTemplate)
				reasonTemplate.SelectedIndexChanged += new EventHandler(reasonTemplate_SelectedIndexChanged);

			if (null != deleteButton)
				deleteButton.Click += new System.EventHandler(DeletePost_Click);

			if (null != cancelButton)
				cancelButton.Click += new EventHandler(CancelDelete_Click);
		}

        #endregion

        #region Event Handlers
        
        // *********************************************************************
        //  DeletePost_Click
        //
        /// <summary>
        /// Event handler for deleting a post
        /// </summary>
        // ***********************************************************************/
        private void DeletePost_Click(Object sender, EventArgs e)
        {
            // Are we valid?
            if (Page.IsValid)
            {
                // Get the post we are going to delete
                //
                ForumPost post = (ForumPost) Posts.GetPost(csContext.PostID, CSContext.Current.User.UserID);

                // get the old ForumID to redirect to, before we delete it and
                // loose this information.
                //
                int oldForumID = post.SectionID;

                // Perform the delete
                //
				if (deleteChildren != null)
					Moderate.DeletePost(post, csContext.User, reasonForDelete.Text, deleteChildren.SelectedValue);
				else
					Moderate.DeletePost(post, csContext.User, reasonForDelete.Text, false);

                // Did we delete a thread?
                //
                if (csContext.ReturnUrl != String.Empty) 
                {
                    csContext.Context.Response.Redirect(csContext.ReturnUrl, true);
                } 
                else 
                {
                    csContext.Context.Response.Redirect(ForumUrls.Instance().Forum(oldForumID), true);
                }
            }
        }

        // *********************************************************************
        //  CancelDelete_Click
        //
        /// <summary>
        /// Event handler for canceling deletion of a post
        /// </summary>
        // ***********************************************************************/
        private void CancelDelete_Click(Object sender, EventArgs e) 
        {
            csContext.Context.Response.Clear();
            csContext.Context.Response.Redirect(csContext.ReturnUrl, true);
        }

		private void reasonTemplate_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (reasonTemplate != null)
			{
				template = ResourceManager.GetTemplate(Int32.Parse(reasonTemplate.SelectedValue)).Body;
				template = template.Replace("[SiteName]", csContext.SiteSettings.SiteName);
				template = template.Replace("[PostBody]", Context.Server.HtmlDecode(Formatter.RemoveHtml(postToDelete.Body)));
				template = template.Replace("[ParentLink]", Globals.FullPath(Globals.GetSiteUrls().Post(postToDelete.ParentID)));

				if (reasonForDelete != null)
					reasonForDelete.Text = template;
			}
		}

		#endregion
	}
}
