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 options : PageTemplate.OrciidPage
	{
		protected System.Web.UI.WebControls.Button SaveOptionsButton;
		protected System.Web.UI.WebControls.DropDownList FontSizeDropDownList;
		protected System.Web.UI.WebControls.DropDownList StartPageDropDownList;
		protected System.Web.UI.WebControls.CheckBoxList HideCollectionsCheckBoxList;
		protected System.Web.UI.WebControls.RadioButtonList SlideshowSelectionScreenRadioButtonList;
		protected System.Web.UI.WebControls.RadioButtonList AddSlidesToAreaRadioButtonList;
		protected System.Web.UI.WebControls.RadioButtonList TargetPageAfterSlideAddRadioButtonList;
		protected System.Web.UI.WebControls.TextBox CurrentPasswordTextBox;
		protected System.Web.UI.WebControls.TextBox NewPasswordTextBox;
		protected System.Web.UI.WebControls.TextBox NewPasswordRepeatTextBox;
		protected System.Web.UI.WebControls.Button ChangePasswordButton;
		protected System.Web.UI.HtmlControls.HtmlGenericControl PasswordDiv;
		protected System.Web.UI.WebControls.Label InvalidCurrentPasswordLabel;
		protected System.Web.UI.WebControls.Label PasswordsDoNotMatchLabel;
		protected System.Web.UI.WebControls.Label PasswordChangedSuccessfullyLabel;
		protected System.Web.UI.WebControls.Label NewPasswordBlankLabel;
		protected System.Web.UI.WebControls.Repeater GroupMembershipRepeater;
		protected System.Web.UI.WebControls.CheckBox SkipMenuLinkCheckBox;
		protected System.Web.UI.HtmlControls.HtmlGenericControl Heading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl PasswordChangeHeading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl CurrentPasswordLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl NewPasswordLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl RepeatNewPasswordLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl SettingsHeading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl UserInterfaceHeading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl FontSizeLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl StartPageLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl AddingImagesHeading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl WhenAddingImagesLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl AddNewSlidesLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl AfterAddingImagesLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl CollectionsHeading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl HideCollectionsLabelParagraph;
		protected System.Web.UI.HtmlControls.HtmlGenericControl AccessibilityHeading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl GroupMembershipsHeading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl MembershipsLabelParagraph;
		protected System.Web.UI.HtmlControls.HtmlGenericControl CollectionsDiv;
		
	
		private void SelectRadioButtonListEntry(RadioButtonList list, string entry)
		{
			foreach (ListItem item in list.Items)
				if (item.Value == entry)
				{
					item.Selected = true;
					return;
				}
			list.SelectedIndex = 0;
		}

		private void Page_Load(object sender, System.EventArgs e)
		{
			if (!IsPostBack)
			{
				FontSizeDropDownList.Items.Clear();
				FontSizeDropDownList.Items.Add(new ListItem(GetLocalString(this, "NormalFontSize", "Normal"), "N"));
				FontSizeDropDownList.Items.Add(new ListItem(GetLocalString(this, "LargeFontSize", "Large"), "L"));

				SlideshowSelectionScreenRadioButtonList.Items.Clear();
				SlideshowSelectionScreenRadioButtonList.Items.Add(new ListItem(
					GetLocalString(this, "ShowSelectionScreen", "show slideshow selection screen"), "select"));
				SlideshowSelectionScreenRadioButtonList.Items.Add(new ListItem(
					GetLocalString(this, "UseCurrentSlideshow", "use current slideshow (if available)"), "current"));

				AddSlidesToAreaRadioButtonList.Items.Clear();
				AddSlidesToAreaRadioButtonList.Items.Add(new ListItem(
					GetLocalString(this, "AddSlidesToPresAreaIfEmpty", "to the presentation area if the slideshow is empty, to the scratch area otherwise"), "auto"));
				AddSlidesToAreaRadioButtonList.Items.Add(new ListItem(
					GetLocalString(this, "AddSlidesToPresArea", "to the presentation area"), "presentation"));
				AddSlidesToAreaRadioButtonList.Items.Add(new ListItem(
					GetLocalString(this, "AddSlidesToScratchArea", "to the scratch area"), "scratch"));

				TargetPageAfterSlideAddRadioButtonList.Items.Clear();
				TargetPageAfterSlideAddRadioButtonList.Items.Add(new ListItem(
					GetLocalString(this, "ShowPropertiesPage", "show slideshow properties page"), "properties"));
				TargetPageAfterSlideAddRadioButtonList.Items.Add(new ListItem(
					GetLocalString(this, "ShowLightTable", "jump directly to Light Table"), "lighttable"));

				Orciid.Core.User user = Orciid.Core.User.CurrentUser();
				Properties props = Properties.GetProperties(user);
				string fontsize = props.Get("uifontsize", "N");
				foreach (ListItem item in FontSizeDropDownList.Items)
				{
					if (item.Value == fontsize)
					{
						item.Selected = true;
						break;
					}
				}
				string startpage = props.Get("uistartpage", "announcements");
				StartPageDropDownList.Items.Add(new ListItem(
					GetLocalString(this, "AnnouncementsPage", "Announcements"), "announcements"));
				if (((PageTemplate.OrciidPage)Page).UserCanBuildSlideshows)
					StartPageDropDownList.Items.Add(new ListItem(
					GetLocalString(this, "MySlideshowsPage", "My Slideshows"), "slideshows"));
				if (Orciid.Core.User.HasPrivilegeOnAny('S', user, 
					Privilege.ViewSlideshow, Privilege.ModifySlideshow, Privilege.CopySlideshow) ||
					Orciid.Core.User.HasPrivilege(Privilege.CreateSlideshow, user))
					StartPageDropDownList.Items.Add(new ListItem(
					GetLocalString(this, "SlideshowsPage", "Slideshows"), "viewslideshows"));
				if (Orciid.Core.User.HasPrivilegeOnAny('C', user, Privilege.ReadCollection))
				{
					StartPageDropDownList.Items.Add(new ListItem(
						GetLocalString(this, "FavoriteImagesPage", "Favorite Images"), "favorites"));
					StartPageDropDownList.Items.Add(new ListItem(
						GetLocalString(this, "SearchPage", "Search"), "search"));
					StartPageDropDownList.Items.Add(new ListItem(
						GetLocalString(this, "BrowsePage", "Browse"), "browse"));
				}				
				if (Orciid.Core.User.HasPrivilegeOnAny('C', user, Privilege.PersonalImages))
					StartPageDropDownList.Items.Add(new ListItem(
					GetLocalString(this, "PersonalImagesPage", "Personal Images"), "personalcollection"));
				foreach (ListItem item in StartPageDropDownList.Items)
				{
					if (item.Value == startpage)
					{
						item.Selected = true;
						break;
					}
				}
				if (((PageTemplate.OrciidPage)Page).UserCanBuildSlideshows)
				{
					CollectionsDiv.Visible = true;
					string[] hidecollections = props.Get("uihidecolls", "").Split(new char[] {','});
					foreach (Collection coll in Collection.GetCollections())
					{
						ListItem item = new ListItem(coll.Title, coll.ID.ToString());
						item.Selected = true;
						foreach (string s in hidecollections)
							if (s == item.Value)
							{
								item.Selected = false;
								break;
							}
						HideCollectionsCheckBoxList.Items.Add(item);
					}
					SelectRadioButtonListEntry(
						SlideshowSelectionScreenRadioButtonList,props.Get("addslidestoshow", "select"));
					SelectRadioButtonListEntry(
						AddSlidesToAreaRadioButtonList, props.Get("addslidestoarea", "auto"));
					SelectRadioButtonListEntry(
						TargetPageAfterSlideAddRadioButtonList, props.Get("goafteraddslides", "properties"));
					if (HideCollectionsCheckBoxList.Items.Count == 0)
						CollectionsDiv.Visible = false;				
				}
				else
					CollectionsDiv.Visible = false;
				SkipMenuLinkCheckBox.Checked = (props.GetAsInt("acskipmenulink", 0) == 1);
				PasswordDiv.Visible = (user.AuthenticationType == "internal");
				ArrayList groupmembership = new ArrayList();
				UserGroup[] groups = UserGroup.FindUser(user);
				if (groups != null)
				{
					foreach (UserGroup group in groups)
						groupmembership.Add(group.Title);
					groupmembership.Sort();
				}
				GroupMembershipRepeater.DataSource = groupmembership;
				GroupMembershipRepeater.DataBind();
			}
		}

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

		protected override bool CheckUserPrivileges(Orciid.Core.User user)
		{
			return (user != null && user.ID > 0 && 
				Orciid.Core.User.HasPrivilege(Privilege.UserOptions, user));
		}
 
		#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.ChangePasswordButton.Click += new System.EventHandler(this.ChangePasswordButton_Click);
			this.SaveOptionsButton.Click += new System.EventHandler(this.SaveOptionsButton_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void SaveOptionsButton_Click(object sender, System.EventArgs e)
		{
			Orciid.Core.User user = Orciid.Core.User.CurrentUser();
			Properties props = Properties.GetProperties(user);
			props.Set("uifontsize", FontSizeDropDownList.SelectedValue);
			Session["FontSize"] = FontSizeDropDownList.SelectedValue;
			props.Set("uistartpage", StartPageDropDownList.SelectedValue);
			string hidecollections = "";
			foreach (ListItem item in HideCollectionsCheckBoxList.Items)
				if (!item.Selected)
					hidecollections += (hidecollections.Length > 0 ? "," : "") + item.Value;
			props.Set("uihidecolls", hidecollections);
			props.SetAsInt("acskipmenulink", (SkipMenuLinkCheckBox.Checked ? 1 : 0));
			props.Set("addslidestoshow", SlideshowSelectionScreenRadioButtonList.SelectedValue);
			props.Set("addslidestoarea", AddSlidesToAreaRadioButtonList.SelectedValue);
			props.Set("goafteraddslides", TargetPageAfterSlideAddRadioButtonList.SelectedValue);
			Response.Redirect(StartPageDropDownList.SelectedValue + ".aspx");
		}

		private void ChangePasswordButton_Click(object sender, System.EventArgs e)
		{
			Orciid.Core.User user = Orciid.Core.User.CurrentUser();
			if (user.AuthenticationType == "internal")
			{
				string oldpw = CurrentPasswordTextBox.Text;
				string newpw = NewPasswordTextBox.Text;
				string newpw2 = NewPasswordRepeatTextBox.Text;
				Orciid.Core.User checkuser = Orciid.Core.User.GetByLogin(user.Login, oldpw);
				if (checkuser != null && checkuser.IsAuthenticated)
				{
					if (newpw != null && newpw.Length > 0)
					{
						if (newpw == newpw2)
						{
							user.SetPassword(newpw);
							this.PasswordChangedSuccessfullyLabel.Visible = true;
						}
						else
							PasswordsDoNotMatchLabel.Visible = true;
					}
					else
						NewPasswordBlankLabel.Visible = true;
				}
				else
					InvalidCurrentPasswordLabel.Visible = true;
			}
		}

	}
}
