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 viewslideshows : PageTemplate.OrciidPage
	{
		protected System.Web.UI.WebControls.DropDownList OwnerDropDownList;
		protected System.Web.UI.WebControls.DropDownList FolderDropDownList;
		protected System.Web.UI.WebControls.Label NoSlideshowsLabel;
		protected System.Web.UI.WebControls.DataGrid SlideshowDataGrid;
		private int[] showids = null;
		private bool[] haspassword = null;
		protected System.Web.UI.HtmlControls.HtmlGenericControl Heading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl AuthorLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl FolderLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl AcrobatNoteSpan;
		private Hashtable userids = null;

		private bool usercancreateslideshows = false;

		private class ListItemComparer : IComparer  
		{
			int IComparer.Compare(Object x, Object y)  
			{
				return String.Compare((x as ListItem).Text, (y as ListItem).Text);
			}
		}

		private void Page_Load(object sender, System.EventArgs e)
		{
			usercancreateslideshows = Orciid.Core.User.HasPrivilege(Privilege.CreateSlideshow);
			if (!IsPostBack)
			{
				OwnerDropDownList.Items.Clear();
				userids = Orciid.Core.User.GetBySlideshows();
				if (userids != null)
				{
					int[] u = new int[userids.Count];
					userids.Keys.CopyTo(u, 0);
					Orciid.Core.User[] users = Orciid.Core.User.GetByID(u);
					if (users != null)
					{
						ArrayList sorted = new ArrayList();
						foreach (User user in users)
							if (user != null)
								sorted.Add(
									new ListItem(user.FullName, user.ID.ToString()));
						sorted.Sort(new ListItemComparer());
						OwnerDropDownList.Items.AddRange((ListItem[])sorted.ToArray(typeof(ListItem)));
					}
				}
				DataBindFolderList();
				RecallSelections();
				if (OwnerDropDownList.Items.Count == 0)
					OwnerDropDownList.Items.Add(new ListItem(
						GetLocalString(this, "NoAuthorsAvailable", "[No slideshow authors available]"), ""));
			}			
		}

		private void AddFolderToListIfHasSlideshows(int[] folderids, int folderid, string foldername)
		{
			foreach (int i in folderids)
				if (i == folderid)
					FolderDropDownList.Items.Add(new ListItem(foldername, i.ToString()));
		}

		private void DataBindFolderList()
		{
			showids = null;
			haspassword = null;
			FolderDropDownList.Items.Clear();
			if (OwnerDropDownList.Items.Count > 0 && 
				OwnerDropDownList.SelectedValue != null &&
				OwnerDropDownList.SelectedValue.Length > 0)
			{
				int ownerid = Int32.Parse(OwnerDropDownList.SelectedValue);
				Orciid.Core.User owner = Orciid.Core.User.GetByID(ownerid);
				SortedList userfolders = owner.GetFolders();
				int[] folderids = null;
				if (userids != null && userids.ContainsKey(owner.ID))
					folderids = (int[])userids[owner.ID];
				if (folderids != null)
				{
					AddFolderToListIfHasSlideshows(folderids, 0, GetLocalString(this, "MainFolder", "[Main]"));
					foreach (string foldername in userfolders.Keys)
						AddFolderToListIfHasSlideshows(folderids, 
							(int)userfolders[foldername], foldername);
				}
			}
			DataBindSlideshowDataGrid();
		}

		private void DataBindSlideshowDataGrid()
		{
			if (FolderDropDownList.Items.Count > 0)
			{
				int ownerid = Int32.Parse(OwnerDropDownList.SelectedValue);
				int folderid = Int32.Parse(FolderDropDownList.SelectedValue);
				Slideshow[] shows = Slideshow.GetByFolder(ownerid, folderid);
				showids = new int[shows.Length];
				haspassword = new bool[shows.Length];
				for (int i = 0; i < shows.Length; i++)
				{
					showids[i] = shows[i].ID;
					haspassword[i] = shows[i].IsPasswordProtected();
				}
				if (shows.Length == 0)
				{
					NoSlideshowsLabel.Visible = true;
					SlideshowDataGrid.Visible = false;
				}
				else
				{
					NoSlideshowsLabel.Visible = false;
					SlideshowDataGrid.Visible = true;
					SlideshowDataGrid.DataSource = shows;
					SlideshowDataGrid.DataBind();
					// hide empty columns
					bool hidepropertiescolumn = true;
					foreach (DataGridItem item in SlideshowDataGrid.Items)
						if (item.Cells[3].FindControl("PropertiesLinkButton").Visible)
						{
							hidepropertiescolumn = false;
							break;
						}
					SlideshowDataGrid.Columns[3].Visible = !hidepropertiescolumn;
					bool hidecopyshowcolumn = true;
					foreach (DataGridItem item in SlideshowDataGrid.Items)
						if (item.Cells[4].FindControl("CopyShowLinkButton").Visible)
						{
							hidecopyshowcolumn = false;
							break;
						}
					SlideshowDataGrid.Columns[4].Visible = !hidecopyshowcolumn;
				}
			}
			else
			{
				NoSlideshowsLabel.Visible = true;
				SlideshowDataGrid.Visible = false;
			}
		}

		protected override void LoadViewState(object savedState)
		{
			if (savedState != null)
			{
				base.LoadViewState(savedState);
				showids = (int[])ViewState["showids"];
				haspassword = (bool[])ViewState["haspassword"];
				userids = (Hashtable)ViewState["userids"];
			}
		}

		protected override object SaveViewState()
		{
			ViewState["showids"] = showids;
			ViewState["haspassword"] = haspassword;
			ViewState["userids"] = userids;
			return base.SaveViewState();
		}

		#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.OwnerDropDownList.SelectedIndexChanged += new System.EventHandler(this.OwnerDropDownList_SelectedIndexChanged);
			this.FolderDropDownList.SelectedIndexChanged += new System.EventHandler(this.FolderDropDownList_SelectedIndexChanged);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		protected override bool CheckUserPrivileges(Orciid.Core.User user)
		{
			return true;
		}

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

		private void RememberSelections()
		{
			Session["LastViewSlideshow"] = String.Format("{0}:{1}", 
				OwnerDropDownList.SelectedValue, FolderDropDownList.SelectedValue);
		}

		private void RecallSelections()
		{
			if (Session["LastViewSlideshow"] == null)
				return;
			string[] s = ((string)Session["LastViewSlideshow"]).Split(new char[] { ':' });
			OwnerDropDownList.SelectedValue = s[0];
			DataBindFolderList();
			FolderDropDownList.SelectedValue = s[1];
			DataBindSlideshowDataGrid();
		}

		private void OwnerDropDownList_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			DataBindFolderList();
			RememberSelections();
		}

		private void FolderDropDownList_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			DataBindSlideshowDataGrid();
			RememberSelections();
		}

		protected void PropertiesLinkButton_OnClick(object sender, System.EventArgs e)
		{
			LinkButton button = sender as LinkButton;
			DataGridItem item = button.Parent.Parent as DataGridItem;
			if (showids != null && item.ItemIndex < showids.Length)
				Response.Redirect(String.Format("slideshow.aspx?id={0}", showids[item.ItemIndex]));
			else
				throw new Exception("Internal error: Show ID not found");
		}

		protected void PropertiesLinkButton_OnDataBinding(object sender, System.EventArgs e)
		{
			LinkButton button = sender as LinkButton;
			DataGridItem item = button.Parent.Parent as DataGridItem;
			button.Visible = Orciid.Core.User.HasPrivilege(Privilege.ModifySlideshow, (Slideshow)item.DataItem);
		}

		protected void CopyShowLinkButton_OnClick(object sender, System.EventArgs e)
		{
			LinkButton button = sender as LinkButton;
			DataGridItem item = button.Parent.Parent as DataGridItem;
			if (showids != null && item.ItemIndex < showids.Length)
			{
				Slideshow show = Slideshow.GetByID(showids[item.ItemIndex]);
/*				Slideshow copy = new Slideshow();
				copy.Title = "Copy of " + show.Title;
				foreach (Slide slide in show.GetSlides())
				{
					Slide newslide = new Slide();
					newslide.ImageID = slide.ImageID;
					newslide.Scratch = slide.Scratch;
					newslide.Annotation = slide.Annotation;
					copy.Add(newslide);
				}	
				copy.Update();
*/
				Slideshow copy = show.CreateCopy();
				Response.Redirect(String.Format("slideshow.aspx?id={0}", copy.ID));
			}
			else
				throw new Exception("Internal error: Show ID not found");
		}

		protected void CopyShowLinkButton_OnDataBinding(object sender, System.EventArgs e)
		{
			LinkButton button = sender as LinkButton;
			DataGridItem item = button.Parent.Parent as DataGridItem;
			button.Visible = usercancreateslideshows &&
				Orciid.Core.User.HasPrivilege(Privilege.CopySlideshow, (Slideshow)item.DataItem);
		}

		protected void ViewSlideshowHyperLink_OnDataBinding(object sender, System.EventArgs e)
		{
			HyperLink button = sender as HyperLink;
			DataGridItem item = button.Parent.Parent as DataGridItem;
			Slideshow show = item.DataItem as Slideshow;
			button.Text = show.Title;
			System.Web.UI.WebControls.Image image = 
				(System.Web.UI.WebControls.Image)item.FindControl("lock");
			image.Visible = (show.IsPasswordProtected());
			if (image.Visible)
			{
				if ((Session["slideshowpassword:" + show.ID.ToString()] as String) != null)
				{
					image.AlternateText = GetLocalString(this, "ProtectedUnlocked", "Password protected (unlocked)");
					image.ImageUrl = "images/unlocked.gif";
				}
				else
				{
					image.AlternateText = GetLocalString(this, "ProtectedLocked", "Password protected (locked)");
					image.ImageUrl = "images/locked.gif";
				}
			}
			button.Visible = CanViewShow(show);
			// if button is hidden, show literal slide show title instead
			Literal alttitle = ((Literal)item.FindControl("AltTitle"));
			alttitle.Text = button.Text;
			alttitle.Visible = !button.Visible;		
		}

		protected void PrintViewHyperLink_OnDataBinding(object sender, System.EventArgs e)
		{
			HyperLink button = sender as HyperLink;
			DataGridItem item = button.Parent.Parent as DataGridItem;
			Slideshow show = item.DataItem as Slideshow;
			button.Visible = CanViewShow(show);
		}

		protected void FlashCardsHyperLink_OnDataBinding(object sender, System.EventArgs e)
		{
			HyperLink button = sender as HyperLink;
			DataGridItem item = button.Parent.Parent as DataGridItem;
			Slideshow show = item.DataItem as Slideshow;
			button.Visible = CanViewShow(show);
		}

		private bool CanViewShow(Slideshow show)
		{
			Orciid.Core.User current = Orciid.Core.User.CurrentUser();
			return show != null && 
				Orciid.Core.User.HasPrivilege(Privilege.ViewSlideshow, show, current) &&
				(!show.ArchiveFlag || (current != null && (current.ID == show.Owner || current.Administrator)));
		}

		protected string BuildUrl(int itemindex, string url)
		{
			if (haspassword[itemindex])
				return String.Format("slideshowpassword.aspx?id={0}&url={1}",
					showids[itemindex], Server.UrlEncode(url));
			else
				return url;
		}
	}
}
