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 slideshow : PageTemplate.OrciidPage
	{
		protected System.Web.UI.HtmlControls.HtmlGenericControl Title;
		protected System.Web.UI.WebControls.LinkButton SelectSlidesLinkButton;
		protected System.Web.UI.WebControls.TextBox TitleTextBox;
		protected System.Web.UI.WebControls.Button RenameButton;
		protected System.Web.UI.WebControls.DropDownList FolderDropDownList;
		protected System.Web.UI.WebControls.Button MoveButton;
		protected System.Web.UI.WebControls.Label CreatedLabel;
		protected System.Web.UI.WebControls.Label ModifiedLabel;
		protected System.Web.UI.WebControls.Label SlidesLabel;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ViewSlidesSpan;
		protected System.Web.UI.WebControls.LinkButton DeleteLinkButton;
		protected System.Web.UI.WebControls.LinkButton LightTableLinkButton;
		protected System.Web.UI.WebControls.LinkButton ViewLinkButton;
		protected System.Web.UI.WebControls.LinkButton ArchiveLinkButton;
		protected System.Web.UI.WebControls.Label ArchiveLabel;
		protected System.Web.UI.WebControls.LinkButton AddImagesLinkButton;
		protected System.Web.UI.WebControls.LinkButton PackageLinkButton;
		protected System.Web.UI.WebControls.HyperLink PrintViewHyperLink;
		protected System.Web.UI.WebControls.HyperLink FlashCardHyperLink;
		protected System.Web.UI.WebControls.Label FolderLabel;
		protected System.Web.UI.HtmlControls.HtmlGenericControl FolderSpan;
		protected System.Web.UI.HtmlControls.HtmlTableRow OwnerTableRow;
		protected System.Web.UI.WebControls.Label OwnerLabel;
		protected System.Web.UI.HtmlControls.HtmlGenericControl DeleteButtonSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl PermissionsButtonSpan;
		protected System.Web.UI.WebControls.HyperLink PermissionsHyperLink;
		protected System.Web.UI.WebControls.LinkButton DuplicateLinkButton;
		protected System.Web.UI.HtmlControls.HtmlGenericControl DuplicateButtonSpan;
		protected System.Web.UI.WebControls.TextBox PasswordTextBox;
		protected System.Web.UI.WebControls.Button SetPasswordButton;
		protected System.Web.UI.WebControls.Button RemovePasswordButton;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ArchiveLinkButtonSpan;
		protected System.Web.UI.WebControls.Label DirectLinkLabel;
		protected System.Web.UI.HtmlControls.HtmlGenericControl Heading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl TitleLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl OwnerLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl FolderLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl PasswordLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl CreatedLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ModifiedLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl SlidesLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl StatusLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl DirectLinkLabelSpan;
			
		private Slideshow show;

		private void Page_Load(object sender, System.EventArgs e)
		{
			if (!IsPostBack)
			{
				if (Request.QueryString["id"] == "new")
				{
					show = new Slideshow();
					show.Title = GetLocalString(this, "NewSlideshowTitle", "New Slideshow");
					try
					{
						show.Folder = Int32.Parse(Request.QueryString["folder"]);
					}
					catch
					{
						show.Folder = 0;
					}
					show.Update();
					Session["CurrentSlideshow"] = show.ID;
				}
				else
				{
					try
					{
						show = Slideshow.GetByID(Int32.Parse(Request.QueryString["id"]));
						Session["CurrentSlideshow"] = show.ID;						
					}
					catch
					{
						Response.Redirect("slideshows.aspx"); 
					}	
				}
				TitleTextBox.Text = show.Title;
				if (show.Password != null)
					PasswordTextBox.Text = show.Password;
			}
			else
			{
				show = Slideshow.GetByID((int)Session["CurrentSlideshow"]);
				if (show == null)
					Response.Redirect("slideshows.aspx"); 
			}
			Orciid.Core.User user = Orciid.Core.User.CurrentUser();
			if (user.ID != show.Owner)
			{
				FolderSpan.Visible = false;
				FolderLabel.Visible = true;
				Orciid.Core.User owner = Orciid.Core.User.GetByID(show.Owner);
				FolderLabel.Text = (show.Folder == 0 ? 
					GetLocalString(this, "MainFolder", "[Main]") : owner.GetFolderName(show.Folder));
				OwnerTableRow.Visible = true;
				OwnerLabel.Text = owner.FullName;
				DeleteButtonSpan.Visible = 
					Orciid.Core.User.HasPrivilege(Privilege.DeleteSlideshow, show);
				DuplicateButtonSpan.Visible = 
					Orciid.Core.User.HasPrivilege(Privilege.CopySlideshow, show) &&
					Orciid.Core.User.HasPrivilege(Privilege.CreateSlideshow);
			}
			else
			{
				FolderSpan.Visible = true;
				FolderLabel.Visible = false;
				OwnerTableRow.Visible = false;
				if (!IsPostBack)
					QueryFolderList(show.Folder);
				DeleteButtonSpan.Visible = true;
				DuplicateButtonSpan.Visible = true;
			}

			// even owner cannot always change ACL (needs Privilege.PublishSlideshow on system)
			bool canmodifyacl = show.CanModifyACL(user, false);
			PermissionsButtonSpan.Visible = canmodifyacl;
			ArchiveLinkButtonSpan.Visible = canmodifyacl || !show.ArchiveFlag;
		}

		private void slideshow_PreRender(object sender, System.EventArgs e)
		{
			Title.InnerText = show.Title;
			CreatedLabel.Text = show.CreationDate;
			ModifiedLabel.Text = show.ModificationDate;
			Slide[] slides = show.GetSlides();	
			SlidesLabel.Text = String.Format(slides.Length == 1 ?
				GetLocalString(this, "SlideInSlideshow", "1 slide in this slideshow") :
				GetLocalString(this, "SlidesInSlideshow", "{0} slides in this slideshow"),
				slides.Length);
			ViewSlidesSpan.Visible = (slides.Length > 0);
			DeleteLinkButton.Attributes["onclick"] = "return confirm('" +
				EncodeJavaScriptString(GetLocalString(this, "DeleteConfirmation", 
				"Are you sure you want to delete this slideshow?")) + "');";
			ArchiveLinkButton.Text = (show.ArchiveFlag ? 
				GetLocalString(this, "Unarchive", "Unarchive") : 
				GetLocalString(this, "Archive", "Archive"));
			ArchiveLabel.Text = (show.ArchiveFlag ? 
				GetLocalString(this, "SlideshowArchived", "This slideshow is archived") : 
				GetLocalString(this, "SlideshowNotArchived", "This slideshow is not archived"));
			DirectLinkLabel.Text = Request.Url.GetLeftPart(UriPartial.Authority) + 
				Request.ApplicationPath + 
				(Request.ApplicationPath.EndsWith("/") ? "" : "/") + 
				"default.aspx?direct=slideshow&id=" + show.ID.ToString();
			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);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.RenameButton.Click += new System.EventHandler(this.RenameButton_Click);
			this.MoveButton.Click += new System.EventHandler(this.MoveButton_Click);
			this.SetPasswordButton.Click += new System.EventHandler(this.SetPasswordButton_Click);
			this.RemovePasswordButton.Click += new System.EventHandler(this.RemovePasswordButton_Click);
			this.SelectSlidesLinkButton.Click += new System.EventHandler(this.SelectSlidesLinkButton_Click);
			this.ArchiveLinkButton.Click += new System.EventHandler(this.ArchiveLinkButton_Click);
			this.ViewLinkButton.Click += new System.EventHandler(this.ViewLinkButton_Click);
			this.PrintViewHyperLink.DataBinding += new System.EventHandler(this.PrintViewHyperLink_DataBinding);
			this.FlashCardHyperLink.DataBinding += new System.EventHandler(this.FlashCardHyperLink_DataBinding);
			this.LightTableLinkButton.Click += new System.EventHandler(this.LightTableLinkButton_Click);
			this.PackageLinkButton.Click += new System.EventHandler(this.PackageLinkButton_Click);
			this.AddImagesLinkButton.Click += new System.EventHandler(this.AddImagesLinkButton_Click);
			this.DeleteLinkButton.Click += new System.EventHandler(this.DeleteLinkButton_Click);
			this.PermissionsHyperLink.DataBinding += new System.EventHandler(this.PermissionsHyperLink_DataBinding);
			this.DuplicateLinkButton.Click += new System.EventHandler(this.DuplicateLinkButton_Click);
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.slideshow_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 null;
		}

		private void SelectSlidesLinkButton_Click(object sender, System.EventArgs e)
		{
			ArrayList images = new ArrayList();
			foreach (Slide slide in show.GetSlides())
				if (!images.Contains(slide.ImageID))
					images.Add(slide.ImageID);
			if (images.Count > 0)
			{
				Session["LastSearchResult"] = new ResultPageOptions(
					String.Format(GetLocalString(this, "ResultTitle", "Images in {0}"), show.Title),
					String.Format("slideshow.aspx?id={0}", show.ID),
					GetLocalString(this, "BackToSlideshow", "Back to Slideshow"),
					(ImageIdentifier[])images.ToArray(typeof(ImageIdentifier)));
				Response.Redirect("result.aspx"); 
			}
		}

		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);
			FolderDropDownList.DataSource = folders;
			FolderDropDownList.DataTextField = "Key";
			FolderDropDownList.DataValueField = "Value";
			FolderDropDownList.DataBind();
			foreach (ListItem item in FolderDropDownList.Items)
				if (Int32.Parse(item.Value) == selectedID)
				{
					item.Selected = true;
					break;
				}
			if (FolderDropDownList.SelectedItem == null)
				FolderDropDownList.Items[0].Selected = true;
		}

		private void MoveButton_Click(object sender, System.EventArgs e)
		{
			show.Folder = Int32.Parse(FolderDropDownList.SelectedValue);
			show.Update();
		}

		private void DeleteLinkButton_Click(object sender, System.EventArgs e)
		{
			show.Delete();
			Session["CurrentSlideshow"] = null;
			Response.Redirect("slideshows.aspx"); 
		}

		private void LightTableLinkButton_Click(object sender, System.EventArgs e)
		{
			Response.Redirect(String.Format("lighttable.aspx?ssid={0}&url={1}", 
				show.ID, Server.UrlEncode(String.Format("slideshow.aspx?id={0}", show.ID))));
		}

		private void ViewLinkButton_Click(object sender, System.EventArgs e)
		{
			Response.Redirect(String.Format("slideshowviewer.aspx?ssid={0}&url={1}&label={2}", show.ID,
				Server.UrlEncode(String.Format("slideshow.aspx?id={0}", show.ID)), 
				Server.UrlEncode(GetLocalString(this, "SlideshowPropertiesMenuItem", 
					"SLIDESHOW PROPERTIES"))));
		}

		private void ArchiveLinkButton_Click(object sender, System.EventArgs e)
		{
			show.ArchiveFlag = !show.ArchiveFlag;
			show.Update();
			ArchiveLinkButton.Text = (show.ArchiveFlag ? 
				GetLocalString(this, "Unarchive", "Unarchive") : 
				GetLocalString(this, "Archive", "Archive"));
		}

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

		private void RenameButton_Click(object sender, System.EventArgs e)
		{
			if (TitleTextBox.Text != null && TitleTextBox.Text.Length > 0)
			{
				show.Title = TitleTextBox.Text;
				show.Update();
			}		
		}

		private void PackageLinkButton_Click(object sender, System.EventArgs e)
		{
			Response.Redirect(String.Format("package.aspx?ssid={0}&os=win", show.ID));
		}

		private void PrintViewHyperLink_DataBinding(object sender, System.EventArgs e)
		{
			HyperLink link = sender as HyperLink;
			link.NavigateUrl = String.Format("printshow.aspx?ssid={0}&url={1}", 
				show.ID, Server.UrlEncode(String.Format("slideshow.aspx?id={0}", show.ID)));
		}

		private void FlashCardHyperLink_DataBinding(object sender, System.EventArgs e)
		{
			HyperLink link = sender as HyperLink;
			link.NavigateUrl = String.Format("notecards.aspx?ssid={0}", show.ID);
		}

		private void PermissionsHyperLink_DataBinding(object sender, System.EventArgs e)
		{
			HyperLink link = sender as HyperLink;
			link.NavigateUrl = String.Format("permissions.aspx?type=S&id={0}&url={1}",
				show.ID, Server.UrlEncode(String.Format("slideshow.aspx?id={0}", show.ID)));
		}

		private void DuplicateLinkButton_Click(object sender, System.EventArgs e)
		{
			Slideshow copy = new Slideshow();
			copy.Title = GetLocalString(this, "CopyOf", "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();
			Response.Redirect(String.Format("slideshow.aspx?id={0}", copy.ID));
		}

		private void SetPasswordButton_Click(object sender, System.EventArgs e)
		{
			show.Password = PasswordTextBox.Text;
			show.Update();
		}

		private void RemovePasswordButton_Click(object sender, System.EventArgs e)
		{
			show.Password = null;
			show.Update();
			PasswordTextBox.Text = "";
		}
	}
}
