//------------------------------------------------------------------------------
// <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.ControlPanel.UI;
using CommunityServer.Controls;
using CommunityServer.Files;
using CommunityServer.Files.Components;
using CA = ComponentArt.Web.UI;
using HelpIcon = CommunityServer.ControlPanel.Controls.HelpIcon;

namespace CommunityServer.ControlPanel.Files
{
	/// <summary>
	///		Summary description for FileList1.
	/// </summary>
	public class FileList1 : BaseFilesGridControl
	{
		protected DropDownList CategoryList, PublishedStatusList;
		protected Button Button1;
		protected LinkButton NewPost, Categories;
		protected Modal Modal1;
		protected CommunityServer.ControlPanel.Controls.ResourceControl FeedbackFilterLabel;
		protected CA.Grid Grid1;
		protected Button ActionButton;
		protected HelpIcon Helpicon1;
		protected DropDownList ActionList;

		private void Page_Load(object sender, EventArgs e)
		{
			if(!Page.IsPostBack && !FilesPage.IsCallBack)
			{
				BindFilters();
				ConfigurePage();
				buildGrid();
				Grid.DataBind();

				JavaScript.RegisterRefresh(this.Page);    
			}
		}

		protected override void ConfigureGrid()
		{
			AddGridCheckMarkTemplate("IsApproved");

			string postEditorURL = "FileEditor.aspx?SectionID=##  DataItem.GetMember('SectionID').Text ##&PostID=## DataItem.GetMember('PostID').Text ##";
			AddGridHrefTemplate(postEditorURL, "Subject");



			this.AddGridPublishedDateTemplate("AuthorURL","DisplayName","PostDate") ;
			this.AddGridPagerTemplate("Subject", "Username", "PostDate", "IsApproved") ;
		}

		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");

			ArrayList al = PostCategories.GetCategories(CurrentFolder.SectionID,true);
			foreach(PostCategory pc in al)
			{
				CategoryList.Items.Add(new ListItem(Server.HtmlDecode(pc.Name) ,pc.CategoryID.ToString()));
			}
			CategoryList.Items.Insert(0,new ListItem(CommunityServer.ControlPanel.Components.ResourceManager.GetString("CP_Files_FileList_AllCategories"),"-1"));

			PublishedStatusList.Items.Add(new ListItem(CommunityServer.ControlPanel.Components.ResourceManager.GetString("CP_Files_FileList_AllPublishedStatuses"), "All"));
			PublishedStatusList.Items.Add(new ListItem(CommunityServer.ControlPanel.Components.ResourceManager.GetString("CP_Files_FileList_PublishedStatuses"), "Published"));
			PublishedStatusList.Items.Add(new ListItem(CommunityServer.ControlPanel.Components.ResourceManager.GetString("CP_Files_FileList_UnpublishedStatuses"), "Unpublished"));

		}

		private void ConfigurePage()
		{
			CSContext context = CSContext.Current;

			//int ps = context.GetIntFromQueryString("ps",10);
			int categoryid = context.GetIntFromQueryString("cid",-1);
			ListItem li = CategoryList.Items.FindByValue(categoryid.ToString());
			if(li != null)
				li.Selected = true;

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


           
		}

		protected override void buildGrid()
		{
			CSContext context = CSContext.Current;

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

			FileGalleryThreadQuery query = new FileGalleryThreadQuery();
			query.SectionID = CurrentFolder.SectionID;
			query.ApplicationPostType = FileGalleryPostType.File;
			query.RequireSectionIsActive = !(context.User.IsFileAdministrator || context.User.IsAdministrator);

			if(this.GridMode == CA.GridRunningMode.Callback)
			{
				query.PageSize = this.DefaultPageSize;
				query.PageIndex = Grid.CurrentPageIndex;
			}
			else
				query.PageSize = int.MaxValue - 1;

			if(categoryid > -1)
				query.CategoryID = categoryid;

			query.SortOrder = SortOrder.Descending;
			query.SortBy = EntriesSortBy.PostDate;

			switch (PublishedStatusList.SelectedValue)
			{
				case "All":
					query.OnlyApproved = false;
					query.OnlyUnapproved = false;
					break;

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

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

			ThreadSet ts = Entries.GetEntries(query,false);

			Grid.DataSource = ts.Threads;
			this.RecordCount = ts.TotalRecords;

			base.buildGrid();
           
		}

		private void DeleteFile(int postID)
		{
			if(postID > 0)
			{
				Entry e = Entries.GetEntry(postID);
				
				if(e != null && e.SectionID != CurrentFolder.SectionID)
					throw new CSException(CSExceptionType.SectionNotFound);

				if(e != null)
					Entries.Delete(e);
			}
		}

		#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.Button1.Click += new EventHandler(this.Button1_Click);
			this.NewPost.Click += new EventHandler(this.NewPost_Click);
			this.Categories.Click += new EventHandler(this.Categories_Click);
			this.Grid.DeleteCommand += new CA.Grid.GridItemEventHandler(this.Grid_DeleteCommand);
			this.Grid.ItemCheckChanged += new CA.Grid.ItemCheckChangedEventHandler(this.Grid_ItemCheckChanged);
			this.ActionButton.Click += new EventHandler(this.ActionButton_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

		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) ;

				Entry file = Entries.GetEntry(postID, false);
				if(file != 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(file.IsApproved != isApproved)
							{
								file.IsApproved = isApproved;
								Entries.Update(file);
							}

							break;
						}
						case 3:
						{
							DeleteFile(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(Page.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();
		}

		private void Button1_Click(object sender, EventArgs e)
		{
  
			string url  = "{0}?cid={1}&ip={2}";
			url = string.Format(url,Request.Path,CategoryList.SelectedValue, PublishedStatusList.SelectedValue);
			Response.Redirect(url);
		}

		private void NewPost_Click(object sender, EventArgs e)
		{
			Response.Redirect("FileEditor.aspx");
		}

		private void Categories_Click(object sender, EventArgs e)
		{
			Response.Redirect("FileCategories.aspx");
		}

		private void Grid_DeleteCommand(object sender, CA.GridItemEventArgs e)
		{
			DeleteFile(Globals.SafeInt(e.Item["PostID"].ToString(), 0)); 
		}
	}
}
