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

using System;
using System.Web;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using CA = ComponentArt.Web.UI;
using CommunityServer.Files.Components;
using CommunityServer.Files;
using ResourceControl = CommunityServer.ControlPanel.Controls.ResourceControl;
using HelpIcon = CommunityServer.ControlPanel.Controls.HelpIcon;

namespace CommunityServer.ControlPanel.Files
{
	/// <summary>
	///		Summary description for CommentList.
	/// </summary>
	public class CommentList : BaseFilesGridControl
	{
		protected CA.Grid Grid1;
		protected IButton ActionButton;
		protected HelpIcon Helpicon1;
		protected ResourceControl FeedbackFilterLabel;
		protected DropDownList filterPublished;
		protected IButton FilterButton;
		protected Modal Modal1;
		protected DropDownList ActionList;

		private void Page_Load(object sender, EventArgs e)
		{
			//overload the row size because this is a two line grid
			this.CurrentGridRowSize = 2;

			if(!Page.IsPostBack && !FilesPage.IsCallBack)
			{
				BindFilters();
				buildGrid();
				Grid.DataBind();
			}
		}

		private void BindFilters()
		{
			ActionButton.Attributes.Add("onclick","return validate_click();");

			ActionList.Items.Add(new ListItem(CommunityServer.ControlPanel.Components.ResourceManager.GetString("CP_Moderate_Actions"),"-1"));
			ActionList.Items.Add(new ListItem(CommunityServer.ControlPanel.Components.ResourceManager.GetString("CP_Moderate_Approve"),"1"));
			ActionList.Items.Add(new ListItem(CommunityServer.ControlPanel.Components.ResourceManager.GetString("CP_Moderate_Disapprove"),"2"));
			ActionList.Items.Add(new ListItem(CommunityServer.ControlPanel.Components.ResourceManager.GetString("CP_Moderate_Delete"),"3"));

			ActionButton.Text = CommunityServer.ControlPanel.Components.ResourceManager.GetString("CP_Moderate_Action");

			filterPublished.Items.Add(new ListItem(CommunityServer.ControlPanel.Components.ResourceManager.GetString("Feedback_SelectAll"), "All"));
			filterPublished.Items.Add(new ListItem(CommunityServer.ControlPanel.Components.ResourceManager.GetString("Feedback_FilterPublished"), "Published"));
			filterPublished.Items.Add(new ListItem(CommunityServer.ControlPanel.Components.ResourceManager.GetString("Feedback_FilterNotPublished"), "Unpublished"));

			// Check if preselected values of the filter DropDownLists were passed in the URL
			CSContext context = CSContext.Current;
			ListItem li = null;

			int pid = context.GetIntFromQueryString("pid",-1);

			if(pid > -1)
			{
				this.GridMode = CA.GridRunningMode.Client;
			}
			else
			{
				this.GridMode = CA.GridRunningMode.Callback;    
			}

			li = filterPublished.Items.FindByValue(context.QueryString["ip"]);
			if(li != null)
				li.Selected = true;
            
		}

		private void FilterButton_Click(object sender, EventArgs e)
		{
			string url  = "{0}?ip={1}";
			url = string.Format(url,Request.Path,filterPublished.SelectedValue);
			Response.Redirect(url);
		}
	
		private void Grid_DeleteCommand(object sender, CA.GridItemEventArgs e)
		{
			int postID = Globals.SafeInt(e.Item["PostID"].ToString(), 0) ;
			DeletePost(postID);
		}

		private void DeletePost(int postID)
		{
			EntryComment comment = EntryComments.GetComment(postID, true);
			EntryComments.DeleteComment(postID, comment.ParentID);	
		}

		protected override void buildGrid()
		{

			CSContext context = CSContext.Current;

			int parentid = context.GetIntFromQueryString("pid",-1);
			//int bpt = context.GetIntFromQueryString("bpt",-1);

			FileGalleryThreadQuery query = new FileGalleryThreadQuery();
			query.SectionID = CurrentFolder.SectionID;
			
			if(this.GridMode == CA.GridRunningMode.Callback)
			{
				query.PageSize = this.DefaultPageSize;
				query.PageIndex = Grid.CurrentPageIndex;
			}
			else
				query.PageSize = int.MaxValue - 1;
			
			query.ParentID = parentid;
			query.ApplicationPostType = FileGalleryPostType.Comment;
			query.RequireSectionIsActive = !(context.User.IsFileAdministrator || context.User.IsAdministrator);
			
			switch (Request.QueryString["ip"])
			{
				case "Published":
					query.OnlyApproved = true;
					query.OnlyUnapproved = false;
					break;

				case "Unpublished":
					query.OnlyApproved = false;
					query.OnlyUnapproved = true;
					break;

				default:
					query.OnlyApproved = false;
					query.OnlyUnapproved = false;
					break;
			}

			query.SortOrder = SortOrder.Descending;

			int postID = context.GetIntFromQueryString("pid",-1); 
			if(postID > -1)
				query.ParentID = postID;

			    

			ThreadSet ts = EntryComments.GetComments(query, false);

			Grid.DataSource = ts.Threads;

			this.RecordCount = ts.TotalRecords;

			base.buildGrid();

		}

		public void Grid_ItemCheckChanged(object sender, CA.GridItemCheckChangedEventArgs e)
		{
			//This event is raised on every callback. We only need to handle it on a postback/click
			if(!this.FilesPage.IsCallBack && e.Checked) 
			{
				int postID = Globals.SafeInt(e.Item["PostID"].ToString(), 0) ;

				EntryComment comment = EntryComments.GetComment(postID, false);
				if(comment != null)
				{
					switch (ActionList.SelectedIndex)
					{
						case 1:
						case 2:
							bool isApproved = (ActionList.SelectedIndex == 1);

							//Let's not update a post which does not need it.
							if(comment.IsApproved != isApproved)
							{
								comment.IsApproved = isApproved;
								EntryComments.UpdateComment(comment, CSContext.Current.User.UserID);
							}

							break;
						
						case 3:
						{
							DeletePost(postID);
							break;
						}
					}

				}

			}
			
		}

		public void ActionButton_Click(object sender, EventArgs e)
		{
			//HACK: For now lets redirect the user to the current page to clear any client side checkmarks
			Response.Redirect(HttpContext.Current.Request.Url.ToString()) ;

			//This event should fire after the ItemCheckChanged and 
			// is responsible for binding any data changes back to the grid
			buildGrid();
			Grid.DataBind();
		}

		protected override void ConfigureGrid()
		{
			AddGridCheckMarkTemplate("IsApproved");
			AddGridPublishedDateTemplate("ViewAuthorURL", "DisplayName", "PostDate");
			AddGridPagerTemplate("Subject", "DisplayName", "PostDate", "IsApproved");
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
			this.Grid.ItemCheckChanged += new CA.Grid.ItemCheckChangedEventHandler(this.Grid_ItemCheckChanged);
			this.Grid.DeleteCommand += new CA.Grid.GridItemEventHandler(this.Grid_DeleteCommand);
			this.ActionButton.Click += new EventHandler(this.ActionButton_Click);
			this.FilterButton.Click += new EventHandler(this.FilterButton_Click);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new EventHandler(this.Page_Load);

		}

		#endregion
	}
}
