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

using System;
using System.Data;
using System.Web.UI.WebControls;
using System.Collections;
using CommunityServer.Files.Components;
using CommunityServer.Components;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using CA = ComponentArt.Web.UI;
using ResourceManager = CommunityServer.ControlPanel.Components.ResourceManager;
using CSFolders = CommunityServer.Files.Components.Folders;

namespace CommunityServer.ControlPanel.FileAdmin
{
	/// <summary>
	///		Summary description for FolderListControl.
	/// </summary>
	public class FolderListControl : BaseFilesAdminGridControl
	{

		#region Child Controls

		protected CA.Grid Grid1;
		protected CheckBox chkConfirmInsert;
		protected CheckBox chkConfirmUpdate;
		protected CheckBox chkConfirmDelete;
		protected Modal Modal1;
		protected ResourceControl FeedbackFilterLabel;
		protected DropDownList AdminGroupList;
		protected ResourceControl Resourcecontrol1;

		#endregion

		private int groupID = CSContext.Current.GetIntFromQueryString("GroupID",-1);

		private bool HasGroupFilter
		{
			get{return groupID != -1;}
		}

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

		}

		#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.AdminGroupList.SelectedIndexChanged += new EventHandler(this.AdminGroupList_SelectedIndexChanged);
			this.Grid.DeleteCommand += new CA.Grid.GridItemEventHandler(this.Grid_DeleteCommand);
		}
		
		/// <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);
			this.EnableSearchBox = true;
		}
		#endregion

		private void BindGroupList()
		{
			ArrayList groups = CSFolders.GetFolderGroups(false, true, false);
			foreach(Group group in groups)
				AdminGroupList.Items.Add(new ListItem(group.Name, group.GroupID.ToString()));
	
			AdminGroupList.Items.Insert(0,new ListItem(ResourceManager.GetString("CP_FilesAdmin_FolderListControl_AllGroups"),"-1"));
		}

		private void ConfigurePage()
		{
			ListItem li = AdminGroupList.Items.FindByValue(groupID.ToString());
			if(li != null)
				li.Selected = true;
              
		}
		private void UpdateDb(CA.GridItem item, string command)
		{
			//Check to see that the user can administer
			//Ideally we will add conditional formatting on the grid to hide these options too
			if(!CSContext.Current.User.IsFileAdministrator)
				throw new CSException( CSExceptionType.AdministrationAccessDenied );

			Folder f;
			switch (command)
			{
				case "DELETE":
					
					f = CSFolders.GetFolder(int.Parse(item["SectionID"].ToString()), false);
					CSFolders.Delete(f.SectionID);

					break;

				default: 
					throw new NotImplementedException(string.Concat("The {0} command has not yet been implemented!" ,command)); 
			}
		}

		private void Grid_DeleteCommand(object sender, CA.GridItemEventArgs e)
		{
			UpdateDb(e.Item, "DELETE"); 
		}


		protected override void buildGrid()
		{
			ArrayList sections = GetFolders();

			sections = Sections.FilterByAccessControl(sections, Permission.Administer, CSContext.Current.User);
	

			//The grid will only show checkboxes in edit mode if the data source is a DataTable
			DataTable dt = CADataConverter.ToDataTable(sections, typeof(Folder));
			dt.DefaultView.Sort = "ApplicationKey";
			Grid.DataSource = dt;

			this.RecordCount = dt.Rows.Count;

			ApplyUserSettings();

			if(this.EnableGrouping)
			{
				dt.DefaultView.Sort = "GroupName";
				Grid.GroupBy = "GroupName ASC";
			}

		}

		private void AdminGroupList_SelectedIndexChanged(object sender, EventArgs e)
		{
			//TODO: Figure out how to use a CA filter and dump this hack
			//Grid.CurrentPageIndex = 0;
			//Grid.DataBind();
			
			string url  = "{0}?GroupID={1}";
			url = string.Format(url, Request.Path, AdminGroupList.SelectedValue);
			Response.Redirect(url);

		}

		protected ArrayList GetFolders()
		{
			if(HasGroupFilter)
				return CSFolders.GetFoldersByGroupID(groupID, true, true, true);
			else
				return CSFolders.GetFolders(CSContext.Current.User.UserID, true, false, true);
		}

		protected ArrayList GetGroups()
		{
			return CSFolders.GetFolderGroups(false, true, false);
		}

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

			string sectionURL = @"CreateEditFolder.aspx?SelectedNavItem=FileFolders&amp;SectionID=## DataItem.GetMember(""SectionID"").Text ##";
			AddGridHrefTemplate(sectionURL,"","Name", @"## DataItem.GetMember(""Description"").Text ##");
			AddGridHrefTemplate(sectionURL,"ApplicationKey");

			AddGridPagerTemplate("Name", "GroupName","IsActive");
		}


	}
}
