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

using System;
using System.Collections;
using System.Web.UI;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Discussions.Components;

namespace CommunityServer.Discussions.Controls 
{
	// *********************************************************************
	//  ModerationMenu
	//
	/// <summary>
	/// This control renders a moderation menu used by forum moderators
	/// to moderate new posts.
	/// </summary>
	// ********************************************************************/ 	
	public class ModerationPopupMenu : ClientPopulatedPopupMenu, IPostBackEventHandler
	{
	    CSContext csContext;
		bool canModerate = false;
		bool canEdit = false;

		#region Control Event Handlers

		protected override void OnInit(EventArgs e) 
		{
			csContext = CSContext.Current;
			this.ResourceName = "ModerationPopupMenu_Text";
			base.OnInit(e);
		}
		
		protected override void OnLoad(EventArgs e) 
		{
			if (!UserHasAccess)
			{
				this.Visible = false;
				return;
			}

			base.OnLoad(e);
		}

		protected override void OnPreRender(EventArgs e)
		{
			if (!UserHasAccess)
			{
				return;
			}

			this.Parameters = new string[9];
			this.Parameters[0] = this.Post.PostID.ToString();
			this.Parameters[1] = this.Forum.SectionID.ToString();
			this.Parameters[2] = this.Post.IsApproved ? "1" : "0";
			this.Parameters[3] = this.Post.PostLevel.ToString();
			this.Parameters[4] = this.Post.IsLocked ? "1" : "0";
			this.Parameters[5] = canModerate ? "1" : "0";
			this.Parameters[6] = this.Post.User.UserID.ToString();
			this.Parameters[7] = this.Post.User.ModerationLevel.ToString();

			base.OnPreRender(e);
		}

		#endregion

		#region DataBind

		protected override ArrayList ClientMenuItemFormats
		{
			get
			{
				ArrayList formats = new ArrayList();
				ClientMenuItemFormat format;

				// 0 - postID, 1 - sectionID, 2 - IsApproved, 3 - PostLevel, 4 - IsLocked, 5 - CanModerate, 6 - Post User ID, 7 - Post User ModerationLevel

				bool trueRedirect = this.UsePathToRedirect;

				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return parms[2] != 1;')";
				format.Text = ResourceManager.GetString("ModerationMenu_Approve");
				format.ClientSideCommand = Page.GetPostBackClientEvent(this, "Approve:{0}");
				formats.Add(format);

				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return parms[2] != 1;')";
				format.Text = ResourceManager.GetString("ModerationMenu_ApproveView");
				format.ClientSideCommand = Page.GetPostBackClientEvent(this, "ApproveView:{0}");
				formats.Add(format);

				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return parms[2] == 1;')";
				format.Text = ResourceManager.GetString("ModeratePost_EditPost");
				format.NavigateUrl = Globals.GetSiteUrls().ModeratePostEdit(99999, Globals.UrlEncode(Globals.GetSiteUrls().Post(99999))).Replace("99999", "{0}");
				formats.Add(format);

				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return parms[3] == 1')";
				format.Text = ResourceManager.GetString("ModerationMenu_DeleteThread");
				format.NavigateUrl = Globals.GetSiteUrls().ModeratePostDelete(99999, Globals.UrlEncode(ForumUrls.Instance().Forum(this.Post.Forum.SectionID))).Replace("99999", "{0}");
				formats.Add(format);

				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return parms[3] != 1')";
				format.Text = ResourceManager.GetString("ModerationMenu_DeletePost");
				format.NavigateUrl = Globals.GetSiteUrls().ModeratePostDelete(99999, Globals.UrlEncode(ForumUrls.Instance().Forum(this.Post.Forum.SectionID))).Replace("99999", "{0}");
				formats.Add(format);
		
				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return parseInt(parms[3]) > 1')";
				format.Text = ResourceManager.GetString("ModerateThread_Split");
				format.NavigateUrl = Globals.GetSiteUrls().ModerateThreadSplit(99999, Globals.UrlEncode(ForumUrls.Instance().Forum(this.Post.Forum.SectionID))).Replace("99999", "{0}");
				formats.Add(format);

				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return parseInt(parms[3]) <= 1')";
				format.Text = ResourceManager.GetString("ModerateThread_Join");
				format.NavigateUrl = Globals.GetSiteUrls().ModerateThreadJoin(99999, Globals.UrlEncode(ForumUrls.Instance().Forum(this.Post.Forum.SectionID))).Replace("99999", "{0}");
				formats.Add(format);

				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return parms[3] == 1')";
				format.Text = ResourceManager.GetString("ModeratePost_Move");
				format.NavigateUrl = Globals.GetSiteUrls().ModeratePostMove(99999, Globals.UrlEncode(ForumUrls.Instance().Forum(this.Post.Forum.SectionID))).Replace("99999", "{0}");
				formats.Add(format);

				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return parms[2] == 1 && parms[3] == 1 && parms[4] == 1')";
				format.Text = ResourceManager.GetString("ModerateThread_UnLock_Thread");
				format.ClientSideCommand = Page.GetPostBackClientEvent(this, "LockUnlock:{0}");
				formats.Add(format);

				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return parms[2] == 1 && parms[3] == 1 && parms[4] != 1')";
				format.Text = ResourceManager.GetString("ModerateThread_Lock_Thread");
				format.ClientSideCommand = Page.GetPostBackClientEvent(this, "LockUnlock:{0}");
				formats.Add(format);

				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return parms[5] == 1 && parms[7] == \\'Unmoderated\\'')";
				format.Text = ResourceManager.GetString("ModerateThread_Moderate_User");
				format.ClientSideCommand = Page.GetPostBackClientEvent(this, "ModerateUnModerateUser:{6}");
				formats.Add(format);

				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return parms[5] == 1 && parms[7] == \\'Moderated\\'')";
				format.Text = ResourceManager.GetString("ModerateThread_UnModerate_User");
				format.ClientSideCommand = Page.GetPostBackClientEvent(this, "ModerateUnModerateUser:{6}");
				formats.Add(format);

				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return true;')";
				format.Text = ResourceManager.GetString("ModeratePost_EditUser");
				format.NavigateUrl = Globals.GetSiteUrls().ControlPanelUserEdit(99999).Replace("99999", "{6}");
				formats.Add(format);

				if (csContext.SiteSettings.EnableUserModerationCounters) 
				{
					format = new ClientMenuItemFormat();
					format.ClientSideDisplayFunction = "new Function('parms', 'return true;')";
					format.Text = ResourceManager.GetString("ModeratePost_ModerationHistory");
					format.NavigateUrl = Globals.GetSiteUrls().ModerationHistory(99999, Globals.UrlEncode(ForumUrls.Instance().Forum(this.Post.Forum.SectionID))).Replace("99999", "{0}");
					formats.Add(format);
				}

				return formats;
			}
		}
        
		#endregion

		#region Properties

		/// <summary>
		/// Property UsePathToRedirect (bool)
		/// </summary>
		public bool UsePathToRedirect
		{
			get 
			{  
				object obj = ViewState["UsePathToRedirect"];
				return obj == null ? false : (bool)obj;
			}
			set {  ViewState["UsePathToRedirect"] = value; }
		}

		private ForumPost post = null;
		public ForumPost Post 
		{
			get 
			{
				return post;
			}
			set 
			{
				post = value;
			}
		}

		private Forum forum = null;
		public Forum Forum 
		{
			get 
			{
				return forum;
			}
			set 
			{
				forum = value;
			}
		}

		protected bool UserHasAccess
		{
			get
			{
				if (Forum != null)
				{
					canModerate = Permissions.ValidatePermissions(Forum, Permission.Moderate, csContext.User);
					canModerate |= csContext.User.IsForumAdministrator;

					canEdit = Permissions.ValidatePermissions(Forum, Permission.EditOthers, csContext.User);

					return (canModerate || canEdit);
				}
				else
					return false;
			}
		}

		#endregion

		#region Events

		public event EventHandler PostModerateRefresh;
		private void OnPostModerateRefresh(EventArgs e)
		{
			if(PostModerateRefresh != null)
				PostModerateRefresh(null, e);
		}

		#endregion

		#region Event Handlers

		// *********************************************************************
		//  Approve_Click
		//
		/// <summary>
		/// Event handler for approving a post
		/// </summary>
		// ***********************************************************************/
		private void Approve_Click(string commandArgument) 
		{   
			int postID = int.Parse(commandArgument);
			ForumPost post = Posts.GetPost(postID, csContext.User.UserID);

			// Approve the post.
			Moderate.ApprovePost(post, csContext.User.UserID);

			//Context.Response.Redirect(Globals.GetSiteUrls().ModerateForum(csContext.SectionID));
			Context.Response.Redirect(Globals.GetSiteUrls().ModerateForum(post.Forum.SectionID));
			Context.Response.End();
		}
        
		// *********************************************************************
		//  UnModerateUser_Click
		//
		/// <summary>
		/// Event handler for unmoderating a user.
		/// </summary>
		// ***********************************************************************/
		private void ModerateUnModerateUser_Click (string commandArgument) 
		{
			User user = Users.GetUser(int.Parse(commandArgument), false, false);
			Moderate.ToggleUserSettings( ModerateUserSetting.ToggleModerate, user, csContext.User.UserID);

			//Basically, if in mod menu then redirect to mod menu - otherwise, you are in forum so redirect to where you are
			if (this.UsePathToRedirect)
			{
				Context.Response.Redirect(Globals.GetSiteUrls().ModerateForum(csContext.SectionID));
				Context.Response.End();
			}
			else
			{
				Context.Response.Redirect(Globals.GetSiteUrls().Post(this.Post.PostID));
				Context.Response.End();
			}
		}

		// *********************************************************************
		//  LockUnlock_Click
		//
		/// <summary>
		/// Event handler for approving a post and replying to the post.
		/// </summary>
		// ***********************************************************************/
		private void LockUnlock_Click (string commandArgument) 
		{
			int postID = int.Parse(commandArgument);
			ForumPost post = Posts.GetPost(postID, csContext.User.UserID);

			// Check for access before submitting
			Permissions.AccessCheck( post.Section, Permission.Moderate, csContext.User, post );

			// Doing this twice just in case the exception thrown from the access check doesn't fully abort execution
			if(Permissions.ValidatePermissions(post.Section, Permission.Moderate, csContext.User, post))
				Moderate.TogglePostSettings(ModeratePostSetting.ToggleLock, post, csContext.User.UserID);

			// Fire an event to refresh the thread
			OnPostModerateRefresh(new EventArgs());
		}

		// *********************************************************************
		//  ApproveView_Click
		//
		/// <summary>
		/// Event handler for approving a post and viewing the post.
		/// </summary>
		// ***********************************************************************/
		private void ApproveView_Click(string commandArgument) 
		{
			int postID = int.Parse(commandArgument);
			ForumPost post = Posts.GetPost(postID, csContext.User.UserID);

			// Approve the post.
			Moderate.ApprovePost(post, csContext.User.UserID);

			// Redirect the user to the Post url.
			Context.Response.Redirect(Globals.GetSiteUrls().Post(postID));
			Context.Response.End();
		}

		#endregion

		#region IPostBackEventHandler Members

		public void RaisePostBackEvent(string eventArgument)
		{
			string[] e = eventArgument.Split(':');
			switch (e[0])
			{
				case "Approve":
					this.Approve_Click(e[1]);
					break;

				case "ApproveView":
					this.ApproveView_Click(e[1]);
					break;

				case "LockUnlock":
					this.LockUnlock_Click(e[1]);
					break;

				case "ModerateUnModerateUser":
					this.ModerateUnModerateUser_Click(e[1]);
					break;
			}	
		}

		#endregion
	}
}


