using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Orciid.Core;

namespace Orciid
{
	public class slideshows : PageTemplate.OrciidPage
	{
		protected System.Web.UI.WebControls.DropDownList FolderList;
		protected System.Web.UI.WebControls.LinkButton NewSlideshowButton;
		protected System.Web.UI.WebControls.DropDownList MoveToFolderList;
		protected System.Web.UI.WebControls.Button MoveToFolderButton;
		protected System.Web.UI.WebControls.Button ArchiveSlideshowsButton;
		protected System.Web.UI.WebControls.Button DeleteSlideshowsButton;
		protected System.Web.UI.WebControls.Button ActivateSlideshowsButton;
		protected System.Web.UI.HtmlControls.HtmlGenericControl FolderHeading;
		protected System.Web.UI.WebControls.LinkButton ManageFoldersButton;
		protected System.Web.UI.WebControls.DataGrid SlideshowGrid;
		protected System.Web.UI.WebControls.Label NoSlideshowsLabel;
		protected System.Web.UI.WebControls.Label MissingImagesLabel;
		protected System.Web.UI.HtmlControls.HtmlTableRow ActionBar;
		protected System.Web.UI.WebControls.DropDownList FilterDropDownList;
		protected System.Web.UI.HtmlControls.HtmlGenericControl Heading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ShowLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl JumpToFolderLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl SelectedSlideshowsLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl MoveToFolderLabelSpan;
	
		private int[] ids;
		private int[] missingimages;
		bool hasmissingimages = false;

		protected override void LoadViewState(object savedState) 
		{
			if (savedState != null)
			{
				base.LoadViewState(savedState);
				if (ViewState["ids"] is Int32[])
					ids = (int[])ViewState["ids"];
				if (ViewState["mi"] is Int32[])
					missingimages = (int[])ViewState["mi"];
			}
		}

		protected override object SaveViewState()
		{
			ViewState["ids"] = ids;
			ViewState["mi"] = missingimages;
			return base.SaveViewState();
		}

		private void QueryFolderList(int selectedID)
		{
			Session["LastFolder"] = selectedID;
			Orciid.Core.User user = Orciid.Core.User.CurrentUser();
			SortedList folders = user.GetFolders();
			folders.Add(GetLocalString(this, "MainFolder", "[Main]"), 0);
			FolderList.DataSource = folders;
			FolderList.DataTextField = "Key";
			FolderList.DataValueField = "Value";
			FolderList.DataBind();
			foreach (ListItem item in FolderList.Items)
				if (Int32.Parse(item.Value) == selectedID)
				{
					item.Selected = true;
					break;
				}
			if (FolderList.SelectedItem == null)
				FolderList.Items[0].Selected = true;
			MoveToFolderList.DataSource = folders.Clone();
			MoveToFolderList.DataTextField = "Key";
			MoveToFolderList.DataValueField = "Value";
			MoveToFolderList.DataBind();
			QuerySlideshowList();
		}

		private void QuerySlideshowList()
		{
			int selectedID = 0;
			if (Session["CurrentSlideshow"] != null)
				selectedID = (int)Session["CurrentSlideshow"];
			Orciid.Core.User user = Orciid.Core.User.CurrentUser();
			ArrayList s = new ArrayList();
			s.AddRange(Slideshow.GetByFolder(user.ID, Int32.Parse(FolderList.SelectedItem.Value)));
			int filter = Int32.Parse(FilterDropDownList.SelectedValue);
			for (int i = s.Count - 1; i >= 0; i--)
				if ((filter == 1 && ((Slideshow)s[i]).ArchiveFlag) ||
					(filter == 2 && !((Slideshow)s[i]).ArchiveFlag))
					s.RemoveAt(i);
			Slideshow[] slideshows = (Slideshow[])s.ToArray(typeof(Slideshow));
			SlideshowGrid.DataSource = slideshows;
			SlideshowGrid.SelectedIndex = -1;
			ids = new int[slideshows.Length];
			for (int i = 0; i < slideshows.Length; i++)
			{
				ids[i] = slideshows[i].ID;
				if (slideshows[i].ID == selectedID)
					SlideshowGrid.SelectedIndex = i;
			}
			SlideshowGrid.DataBind();
			FolderHeading.InnerText = GetLocalString(this, "FolderLabel", "Folder:") + " " + FolderList.SelectedItem.Text;
			bool hasslideshows = (slideshows.Length > 0);
			SlideshowGrid.Visible = hasslideshows;
			ActionBar.Visible = hasslideshows;
			NoSlideshowsLabel.Visible = !hasslideshows;
			MissingImagesLabel.Visible = hasmissingimages;
		}

		private void Page_Load(object sender, System.EventArgs e)
		{
			SlideshowGrid.Visible = true;
			ActionBar.Visible = true;
			NoSlideshowsLabel.Visible = false;
			if (!IsPostBack)
			{
				missingimages = Analysis.GetUnavailableImagesInSlideshows();

				FilterDropDownList.Items.Clear();
				FilterDropDownList.Items.Add(new ListItem(
					GetLocalString(this, "All", "All"), "0"));
				FilterDropDownList.Items.Add(new ListItem(
					GetLocalString(this, "Unarchived", "Unarchived"), "1"));
				FilterDropDownList.Items.Add(new ListItem(
					GetLocalString(this, "Archived", "Archived"), "2"));
				FilterDropDownList.SelectedIndex = 0;

				int lastfolder = 0;
				if (Session["CurrentSlideshow"] != null)
				{
					int id = (int)Session["CurrentSlideshow"];
					Slideshow show = Slideshow.GetByID(id);
					if (show != null)
						lastfolder = show.Folder;
				}
				if (Session["LastFolder"] != null)
					lastfolder = (int)Session["LastFolder"];
				QueryFolderList(lastfolder);
			}
			ActivateSlideshowsButton.Visible = Orciid.Core.User.HasPrivilege(Privilege.PublishSlideshow);
		}

		#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);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.NewSlideshowButton.Click += new System.EventHandler(this.NewSlideshowButton_Click);
			this.ManageFoldersButton.Click += new System.EventHandler(this.ManageFoldersButton_Click);
			this.FilterDropDownList.SelectedIndexChanged += new System.EventHandler(this.FilterDropDownList_SelectedIndexChanged);
			this.FolderList.SelectedIndexChanged += new System.EventHandler(this.FolderList_SelectedIndexChanged);
			this.SlideshowGrid.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.SlideshowGrid_ItemCommand);
			this.ArchiveSlideshowsButton.Click += new System.EventHandler(this.ArchiveSlideshowsButton_Click);
			this.ActivateSlideshowsButton.Click += new System.EventHandler(this.ActivateSlideshowsButton_Click);
			this.DeleteSlideshowsButton.Click += new System.EventHandler(this.DeleteSlideshowsButton_Click);
			this.MoveToFolderButton.Click += new System.EventHandler(this.MoveToFolderButton_Click);
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.slideshows_PreRender);

		}
		#endregion


		protected override bool CheckUserPrivileges(Orciid.Core.User user)
		{
			return Orciid.Core.User.HasPrivilege(Privilege.CreateSlideshow, user) ||
				Orciid.Core.User.HasPrivilegeOnAny('S', user, Privilege.ModifySlideshow, 
				Privilege.DeleteSlideshow, Privilege.ViewSlideshow, 
				Privilege.ModifyACL);
		}

		public override string GetHighlightedMenuItem()
		{
			return "MyMDID_Slideshows";
		}

		private void ArchiveSlideshowsButton_Click(object sender, System.EventArgs e)
		{
			foreach (DataGridItem item in SlideshowGrid.Items)
			{
				CheckBox checkbox = item.Cells[0].FindControl("SelectCheckBox") as CheckBox;
				if (checkbox.Checked)
				{
					int slideshowid = ids[item.ItemIndex];
					Slideshow slideshow = Slideshow.GetByID(slideshowid);
					if (!slideshow.ArchiveFlag)
					{
						slideshow.ArchiveFlag = true;
						slideshow.Update();
					}
				}
			}
			QuerySlideshowList();
		}

		private DataGridItem GetDataGridItem(Control control)
		{
			while (!(control is DataGridItem) && control.Parent != null)
				control = control.Parent;
			return control as DataGridItem;
		}

		protected void DataBindArchivedLiteral(object sender, System.EventArgs e)
		{
			Literal control = sender as Literal;
			DataGridItem item = GetDataGridItem(control);
			Slideshow show = item.DataItem as Slideshow;
			control.Text = (show.ArchiveFlag ? GetLocalString(this, "Archived", "Archived") : "");
		}

		protected void DataBindMissingImagesLiteral(object sender, System.EventArgs e)
		{
			if (missingimages == null)
				return;
			Literal control = sender as Literal;
			DataGridItem item = GetDataGridItem(control);
			Slideshow show = item.DataItem as Slideshow;
			foreach (int id in missingimages)
				if (id == show.ID)
				{
					control.Text = "<b>*</b>";
					hasmissingimages = true;
					return;
				}			
		}

		private void ActivateSlideshowsButton_Click(object sender, System.EventArgs e)
		{
			foreach (DataGridItem item in SlideshowGrid.Items)
			{
				CheckBox checkbox = item.Cells[0].FindControl("SelectCheckBox") as CheckBox;
				if (checkbox.Checked)
				{
					int slideshowid = ids[item.ItemIndex];
					Slideshow slideshow = Slideshow.GetByID(slideshowid);
					if (slideshow.ArchiveFlag)
					{
						slideshow.ArchiveFlag = false;
						slideshow.Update();
					}
				}
			}	
			QuerySlideshowList();
		}

		private void DeleteSlideshowsButton_Click(object sender, System.EventArgs e)
		{
			int current = -1;
			try
			{
				current = (int)Session["CurrentSlideshow"];
			}
			catch
			{
			}
			foreach (DataGridItem item in SlideshowGrid.Items)
			{
				CheckBox checkbox = item.Cells[0].FindControl("SelectCheckBox") as CheckBox;
				if (checkbox.Checked)
				{
					int slideshowid = ids[item.ItemIndex];
					Slideshow slideshow = Slideshow.GetByID(slideshowid);
					slideshow.Delete();
					if (slideshowid == current)
						Session["CurrentSlideshow"] = null;
				}
			}	
			QuerySlideshowList();		
		}

		private void MoveToFolderButton_Click(object sender, System.EventArgs e)
		{
			int target = Int32.Parse(MoveToFolderList.SelectedItem.Value);
			if (target != Int32.Parse(FolderList.SelectedItem.Value))
			{
				foreach (DataGridItem item in SlideshowGrid.Items)
				{
					CheckBox checkbox = item.Cells[0].FindControl("SelectCheckBox") as CheckBox;
					if (checkbox.Checked)
					{
						int slideshowid = ids[item.ItemIndex];
						Slideshow slideshow = Slideshow.GetByID(slideshowid);
						slideshow.Folder = target;
						slideshow.Update();
					}
				}	
				QuerySlideshowList();		
			}
		}

		private void FolderList_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			QueryFolderList(Int32.Parse(FolderList.SelectedItem.Value));
		}

		private void SlideshowGrid_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			int show = ids[e.Item.ItemIndex];
			Session["CurrentSlideshow"] = show;
			if (e.CommandName == "ModifySlides")
			{
				Response.Redirect(String.Format("lighttable.aspx?ssid={0}&url=slideshows.aspx", show));
			}
			else if (e.CommandName == "ViewSlideshow")
			{
				Response.Redirect(String.Format("slideshowviewer.aspx?ssid={0}&url=slideshows.aspx&label={1}", 
					show, Server.UrlEncode(GetLocalString(this, "MySlideshowsMenuItem", "MY SLIDESHOWS"))));
			}
			else if (e.CommandName == "AddImages")
			{
				Response.Redirect("addimages.aspx"); 
			}
			else if (e.CommandName == "Package")
			{
				Response.Redirect(String.Format("package.aspx?ssid={0}", show)); 
			}			
			else if (e.CommandName == "Properties")
			{
				Response.Redirect(String.Format("slideshow.aspx?id={0}", show));
			}
		}

		private void NewSlideshowButton_Click(object sender, System.EventArgs e)
		{

			Response.Redirect(String.Format("slideshow.aspx?id=new&folder={0}", 
				FolderList.SelectedItem.Value));
		}

		private void ManageFoldersButton_Click(object sender, System.EventArgs e)
		{
			Response.Redirect("managefolders.aspx"); 
		}

		private void FilterDropDownList_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			QuerySlideshowList();
		}

		private void slideshows_PreRender(object sender, System.EventArgs e)
		{
			DeleteSlideshowsButton.Attributes["onclick"] = "return confirm('" +
				EncodeJavaScriptString(GetLocalString(this, "DeleteConfirmation", 
				"Are you sure you want to delete the selected slideshows?")) + "');";
		}
	}
}
