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

using System;
using System.Collections;
using System.Data;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using CommunityServer.Galleries.Components;
using CA = ComponentArt.Web.UI;

namespace CommunityServer.ControlPanel.PhotoAdmin
{
	/// <summary>
	///		Summary description for GalleryListControl.
	/// </summary>
	public class GalleryListControl : BaseGalleryAdminGridControl
	{

		#region Child Controls

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

		#endregion

		protected int groupID = CSContext.Current.GetIntFromQueryString("GroupID",-1);
		protected CommunityServer.ControlPanel.Controls.ResourceControl Resourcecontrol1;

		private bool IsEdit = true;

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

		private void Page_Load(object sender, EventArgs e)
		{
			
			if(!Page.IsPostBack && !GalleryAdminPage.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 System.EventHandler(this.Page_Load);
			this.EnableSearchBox = true;
		}
		#endregion

		private void BindGroupList()
		{
			ArrayList groups = GetGroups(); 
			foreach(Group group in groups)
				AdminGroupList.Items.Add(new ListItem(group.Name, group.GroupID.ToString()));
	
			AdminGroupList.Items.Insert(0,new ListItem(Components.ResourceManager.GetString("CP_PhotosAdmin_GroupList_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.IsGalleryAdministrator)
				throw new CSException( CSExceptionType.AdministrationAccessDenied );

			this.IsEdit = true;
			Gallery gallery;

			switch (command)
			{
				
				case "DELETE":
					
					gallery = CommunityServer.Galleries.Galleries.GetGallery(int.Parse(item["SectionID"].ToString()), false) ;
					
					CommunityServer.Galleries.Galleries.Delete( gallery ) ;

					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 = GetGalleries();

			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(Section));
			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 GetGalleries()
		{
			ArrayList unfiltered = CommunityServer.Galleries.Galleries.GetGalleries(CSContext.Current.User.UserID, true, false, IsEdit);

			//HACK: We need to filter the list here until we can get a client side filter in place
			if(!HasGroupFilter)
			{
				return unfiltered;
			}
			else
			{
				ArrayList filtered = new ArrayList();
				foreach(Gallery g in unfiltered)
					if(g.GroupID == groupID)
						filtered.Add(g);

				return filtered;
			}
		}

		protected ArrayList GetGroups()
		{
			return GalleryGroups.GetGroups(true, true, true);
		}

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

			string sectionURL = @"SectionEdit.aspx?SectionID=## DataItem.GetMember(""SectionID"").Text ##";
			AddGridHrefTemplate(sectionURL,"","Name", @"## DataItem.GetMember(""Description"").Text ##");
			AddGridHrefTemplate(sectionURL,"ApplicationKey");
			
			AddGridPagerTemplate("Name", "GroupName","IsActive");
		}


	}
}
