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 collectionproperties : PageTemplate.OrciidPage
	{
		protected System.Web.UI.WebControls.Label CollectionTitleLabel;
		protected System.Web.UI.WebControls.HyperLink PermissionsHyperLink;
		protected System.Web.UI.WebControls.TextBox UsageAgreementTextBox;
		protected System.Web.UI.WebControls.Button UsageAgreementButton;
		protected System.Web.UI.WebControls.Label CollectionTypeLabel;
		protected System.Web.UI.WebControls.Button UpdateButton;
		protected System.Web.UI.WebControls.TextBox NameTextBox;
		protected System.Web.UI.WebControls.TextBox DescriptionTextBox;
		protected System.Web.UI.WebControls.TextBox ResourcePathTextBox;
		protected System.Web.UI.WebControls.TextBox OverviewImageTextBox;
		protected System.Web.UI.WebControls.CheckBox FixedSizeFullCheckBox;
		protected System.Web.UI.WebControls.CheckBox FixedSizeMediumCheckBox;
		protected System.Web.UI.WebControls.CheckBox FixedSizeThumbCheckBox;
		protected System.Web.UI.WebControls.TextBox WidthFullTextBox;
		protected System.Web.UI.WebControls.TextBox WidthMediumTextBox;
		protected System.Web.UI.WebControls.TextBox WidthThumbTextBox;
		protected System.Web.UI.WebControls.TextBox HeightFullTextBox;
		protected System.Web.UI.WebControls.TextBox HeightMediumTextBox;
		protected System.Web.UI.WebControls.TextBox HeightThumbTextBox;
		protected System.Web.UI.WebControls.TextBox QualityFullTextBox;
		protected System.Web.UI.WebControls.TextBox QualityMediumTextBox;
		protected System.Web.UI.WebControls.TextBox QualityThumbTextBox;
		protected System.Web.UI.WebControls.RequiredFieldValidator NameRequiredFieldValidator;
		protected System.Web.UI.WebControls.RangeValidator WidthFullRangeValidator;
		protected System.Web.UI.WebControls.RangeValidator MediumFullRangeValidator;
		protected System.Web.UI.WebControls.RangeValidator HeightFullRangeValidator;
		protected System.Web.UI.WebControls.RangeValidator HeightMediumRangeValidator;
		protected System.Web.UI.WebControls.RangeValidator HeightThumbRangeValidator;
		protected System.Web.UI.WebControls.RangeValidator QualityThumbRangeValidator;
		protected System.Web.UI.WebControls.RangeValidator QualityMediumRangeValidator;
		protected System.Web.UI.WebControls.RangeValidator QualityFullRangeValidator;
		protected System.Web.UI.WebControls.RequiredFieldValidator WidthFullRequiredFieldValidator;
		protected System.Web.UI.WebControls.RequiredFieldValidator WidthMediumRequiredFieldValidator;
		protected System.Web.UI.WebControls.RequiredFieldValidator WidthThumbRequiredFieldValidator;
		protected System.Web.UI.WebControls.RequiredFieldValidator HeightFullRequiredFieldValidator;
		protected System.Web.UI.WebControls.RequiredFieldValidator HeightMediumRequiredFieldValidator;
		protected System.Web.UI.WebControls.RequiredFieldValidator HeightThumbRequiredFieldValidator;
		protected System.Web.UI.WebControls.RequiredFieldValidator QualityFullRequiredFieldValidator;
		protected System.Web.UI.WebControls.RequiredFieldValidator QualityMediumRequiredFieldValidator;
		protected System.Web.UI.WebControls.RequiredFieldValidator QualityThumbRequiredFieldValidator;
		protected System.Web.UI.WebControls.TextBox RemoveConfirmationTextBox;
		protected System.Web.UI.WebControls.Button RemoveButton;
		protected System.Web.UI.WebControls.HyperLink FieldDefinitionsHyperLink;
		protected System.Web.UI.WebControls.HyperLink ControlledListsHyperLink;
		protected System.Web.UI.WebControls.HyperLink ImportDataHyperLink;
		protected System.Web.UI.HtmlControls.HtmlTableRow ResourcePathTableRow;
		protected System.Web.UI.HtmlControls.HtmlTableRow ImageSizesTableRow;
		protected System.Web.UI.HtmlControls.HtmlTableRow OverviewImageTableRow;
		protected System.Web.UI.HtmlControls.HtmlTableRow RemoteUrlTableRow;
		protected System.Web.UI.HtmlControls.HtmlGenericControl LinksDiv;
		protected System.Web.UI.HtmlControls.HtmlGenericControl RemoveDiv;
		protected System.Web.UI.WebControls.Button CreateImageButton;
		protected System.Web.UI.HtmlControls.HtmlGenericControl CreateImageDiv;
		protected System.Web.UI.HtmlControls.HtmlGenericControl UsageAgreementDiv;
		protected System.Web.UI.WebControls.LinkButton ModerateSubmissionsLinkButton;
		protected System.Web.UI.WebControls.TextBox BGColorFullTextBox;
		protected System.Web.UI.WebControls.TextBox BGColorMediumTextBox;
		protected System.Web.UI.WebControls.TextBox BGColorThumbTextBox;
		protected System.Web.UI.WebControls.RegularExpressionValidator BGColorFullRegularExpressionValidator;
		protected System.Web.UI.WebControls.RegularExpressionValidator BGColorMediumRegularExpressionValidator;
		protected System.Web.UI.WebControls.RegularExpressionValidator BGColorThumbRegularExpressionValidator;
		protected System.Web.UI.WebControls.HyperLink SharingHyperLink;
		protected System.Web.UI.WebControls.TextBox RemoteUrlTextBox;
		protected System.Web.UI.WebControls.Label RemoteUrlLabel;
		protected System.Web.UI.WebControls.DropDownList CollectionGroupDropDownList;
		protected System.Web.UI.WebControls.TextBox CacheSizeTextBox;
		protected System.Web.UI.HtmlControls.HtmlTableRow CacheSizeTableRow;
		protected System.Web.UI.HtmlControls.HtmlGenericControl Heading;
		protected System.Web.UI.WebControls.RangeValidator WidthMediumRangeValidator;
		protected System.Web.UI.HtmlControls.HtmlGenericControl PropertiesHeading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl NameLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl TypeLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl DescriptionLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ResourcePathLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl RemoteUrlLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl CacheSizeLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl CacheSizeNotesSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ImageSizesLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl WidthLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl HeightLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl QualityLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl FixedSizeLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl BackgroundColorLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl FullLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl MediumLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ThumbLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl OverviewImageLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl GroupLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl UsageAgreementHeading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl RemoveCollectionHeading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl RemoveCollectionWarningSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl RemoveCollectionConfirmationLabelSpan;
		protected System.Web.UI.WebControls.HyperLink ExportDataHyperLink;
		protected System.Web.UI.WebControls.RangeValidator WidthThumbRangeValidator;
		protected System.Web.UI.HtmlControls.HtmlGenericControl CreateNewImageHeading;
		
		private Collection coll;

		private void Page_Load(object sender, System.EventArgs e)
		{
			if (!IsPostBack)
			{	
				Properties props = null;
				try
				{
					coll = Collection.GetByID(Int32.Parse(Request.QueryString["id"]));
					props = Properties.GetProperties(coll);
					CollectionTypeLabel.Text = this.GetCollectionTypeLabel(coll.Type);
					UsageAgreementTextBox.Text = coll.UsageAgreement;
					NameTextBox.Text = coll.Title;
					DescriptionTextBox.Text = coll.Description;
					ResourcePathTextBox.Text = coll.ResourcePath;
					OverviewImageTextBox.Text = props.Get("repimage", "");
					ImageSettings fullsettings = coll.GetImageSettings(ImageSize.Full);
					ImageSettings mediumsettings = coll.GetImageSettings(ImageSize.Medium);
					ImageSettings thumbsettings = coll.GetImageSettings(ImageSize.Thumbnail);
					FixedSizeFullCheckBox.Checked = fullsettings.fixedsize;
					FixedSizeMediumCheckBox.Checked = mediumsettings.fixedsize;
					FixedSizeThumbCheckBox.Checked = thumbsettings.fixedsize;
					WidthFullTextBox.Text = fullsettings.width.ToString();
					WidthMediumTextBox.Text = mediumsettings.width.ToString();
					WidthThumbTextBox.Text = thumbsettings.width.ToString();
					HeightFullTextBox.Text = fullsettings.height.ToString();
					HeightMediumTextBox.Text = mediumsettings.height.ToString();
					HeightThumbTextBox.Text = thumbsettings.height.ToString();
					QualityFullTextBox.Text = fullsettings.quality.ToString();
					QualityMediumTextBox.Text = mediumsettings.quality.ToString();
					QualityThumbTextBox.Text = thumbsettings.quality.ToString();
					System.Drawing.Color c;
					c = System.Drawing.Color.FromArgb(fullsettings.backgroundcolor);
					BGColorFullTextBox.Text = String.Format("{0:X2}{1:X2}{2:X2}", 
						c.R, c.G, c.B);
					c = System.Drawing.Color.FromArgb(mediumsettings.backgroundcolor);
					BGColorMediumTextBox.Text = String.Format("{0:X2}{1:X2}{2:X2}",
						c.R, c.G, c.B);
					c = System.Drawing.Color.FromArgb(thumbsettings.backgroundcolor);
					BGColorThumbTextBox.Text = String.Format("{0:X2}{1:X2}{2:X2}",
						c.R, c.G, c.B);
					CollectionGroupDropDownList.Items.Clear();
					CollectionGroupDropDownList.Items.Add(new ListItem(GetLocalString(this, "NoGroup", "[none]"), "0"));
					foreach (CollectionGroup group in CollectionGroup.GetCollectionGroups())
					{
						CollectionGroupDropDownList.Items.Add(new ListItem(group.Title, group.ID.ToString()));
						if (coll.Group == group.ID)
							CollectionGroupDropDownList.SelectedValue = group.ID.ToString();
					}
				}
				catch
				{
					coll = null;
				}
				CheckAuthorization();
				RemoteUrlTableRow.Visible = false;
				if (coll.Type == CollectionType.Remote)
				{
					RemoteUrlTableRow.Visible = true;
					RemoteUrlLabel.Visible = false;
					RemoteUrlTextBox.Text = ((RemoteCollection)coll).RemoteUrl;
				}
				if (coll.Type == CollectionType.Internal)
				{
					RemoteUrlTableRow.Visible = true;
					RemoteUrlTextBox.Visible = false;

					string requiressl = Configuration.Instance.ContainsKey("ui.requiressl") ?
						Configuration.Instance.GetString("ui.requiressl") :
						"false";
					string protocol = requiressl == "false" ? "http" : "https";

					RemoteUrlLabel.Text = 
						protocol +
						"://username:password@" +
						Request.Url.GetLeftPart(UriPartial.Authority).Substring( 
							Request.Url.GetLeftPart(UriPartial.Scheme).Length) + 
						Request.ApplicationPath + 
						"," + coll.ID.ToString();
				}

				if (coll is RemoteCollection)
				{
					FieldDefinitionsHyperLink.Visible = false;
					ImportDataHyperLink.Visible = false;
					ExportDataHyperLink.Visible = false;
					SharingHyperLink.Visible = false;
					CacheSizeTextBox.Text = props.GetAsInt("cachesizelimit", 1024).ToString();
				}
				else if (coll is VirtualCollection)
				{
					if (coll is FavoritesCollection)
						PermissionsHyperLink.Visible = true;
					else
						PermissionsHyperLink.Visible = false;
					FieldDefinitionsHyperLink.Visible = false;
					ImportDataHyperLink.Visible = false;	
					ExportDataHyperLink.Visible = false;
					SharingHyperLink.Visible = false;
					ResourcePathTableRow.Visible = false;
					RemoteUrlTableRow.Visible = false;
					CacheSizeTableRow.Visible = false;
					ImageSizesTableRow.Visible = false;
					OverviewImageTableRow.Visible = false;
					UsageAgreementDiv.Visible = false;
					CreateImageDiv.Visible = false;
					RemoveDiv.Visible = false;
				}
				else
				{
					CacheSizeTableRow.Visible = false;
					FieldDefinitionsHyperLink.NavigateUrl =
						String.Format("collectiondef.aspx?id={0}", coll.ID);
					ImportDataHyperLink.NavigateUrl =
						String.Format("import.aspx?id={0}", coll.ID);
					ExportDataHyperLink.NavigateUrl =
						String.Format("export.aspx?id={0}", coll.ID);
				}
				if (Orciid.Core.User.HasPrivilege(Privilege.ManageControlledLists, coll) &&
					(coll.Type == CollectionType.Internal))
					ControlledListsHyperLink.NavigateUrl =
						String.Format("controlledlists.aspx?id={0}", coll.ID);
				else
					ControlledListsHyperLink.Visible = false;
				CreateImageDiv.Visible = 
					Orciid.Core.User.HasPrivilege(Privilege.ModifyImages, coll) &&
					!coll.IsReadOnly;
				RemoveDiv.Visible = 
					Orciid.Core.User.HasPrivilege(Privilege.DeleteCollection, coll) &&
					!(coll is VirtualCollection);
				ModerateSubmissionsLinkButton.Visible = 
					!coll.IsReadOnly &&
					Orciid.Core.User.HasPrivilege(Privilege.ModifyImages, coll);
				if (Orciid.Core.User.HasPrivilege(Privilege.ModifyACL, coll))
				{
					PermissionsHyperLink.NavigateUrl = 
						String.Format("permissions.aspx?type=C&id={0}&url={1}",
						coll.ID, Server.UrlEncode(String.Format("collection.aspx?id={0}", coll.ID)));
					SharingHyperLink.NavigateUrl = 
						String.Format("collectionsharing.aspx?id={0}", coll.ID);
				}
				else
				{
					PermissionsHyperLink.Visible = false;
					SharingHyperLink.Visible = false;
				}
			}
		}

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

		protected override bool CheckUserPrivileges(Orciid.Core.User user)
		{
			return true;
		}
 
		protected override void LoadViewState(object savedState) 
		{
			if (savedState != null)
			{
				base.LoadViewState(savedState);
				coll = null;
				if (ViewState["cid"] != null)
					coll = Collection.GetByID((int)ViewState["cid"]);
				CheckAuthorization();
			}
		}

		protected override object SaveViewState()
		{
			if (coll != null)
				ViewState["cid"] = coll.ID;
			return base.SaveViewState();
		}

		private void CheckAuthorization()
		{
			Privilege[] privs = new Privilege[] { 
				Privilege.DeleteCollection, Privilege.ManageCollection,
				Privilege.ModifyACL, Privilege.ManageControlledLists,
				Privilege.ModifyImages };
			bool authorized = false;
			if (coll != null)
			{
				foreach (Privilege p in privs)
					if (Orciid.Core.User.HasPrivilege(p, coll))
					{
						authorized = true;
						break;
					}
			}
			if (!authorized)
				Response.Redirect("insufficientprivileges.aspx"); 
		}

		#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.ModerateSubmissionsLinkButton.Click += new System.EventHandler(this.ModerateSubmissionsLinkButton_Click);
			this.UpdateButton.Click += new System.EventHandler(this.UpdateButton_Click);
			this.UsageAgreementButton.Click += new System.EventHandler(this.UsageAgreementButton_Click);
			this.CreateImageButton.Click += new System.EventHandler(this.CreateImageButton_Click);
			this.RemoveButton.Click += new System.EventHandler(this.RemoveButton_Click);
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.collectionproperties_PreRender);

		}
		#endregion

		private void collectionproperties_PreRender(object sender, System.EventArgs e)
		{
			CollectionTitleLabel.Text = coll.Title;
		}

		private void UsageAgreementButton_Click(object sender, System.EventArgs e)
		{
			coll.UsageAgreement = UsageAgreementTextBox.Text.Trim();
			coll.Update();
			this.ShowInformation(GetLocalString(this, "UsageAgreementUpdated", "Usage agreement updated."));
		}

		private void UpdateButton_Click(object sender, System.EventArgs e)
		{
			if (IsValid)
			{
				coll.Title = NameTextBox.Text;
				coll.Description = DescriptionTextBox.Text;
				coll.ResourcePath = ResourcePathTextBox.Text;
				Properties props = Properties.GetProperties(coll);
				string o = OverviewImageTextBox.Text;
				props.Set("repimage", (o != null && o.Length > 0 ? o : null));
				ImageSettings i = new ImageSettings();
				i.fixedsize = FixedSizeFullCheckBox.Checked;
				i.width = Int32.Parse(WidthFullTextBox.Text);
				i.height = Int32.Parse(HeightFullTextBox.Text);
				i.quality = Int32.Parse(QualityFullTextBox.Text);
				i.backgroundcolor = Convert.ToInt32(BGColorFullTextBox.Text, 16);
				coll.SetImageSettings(ImageSize.Full, i);
				i.fixedsize = FixedSizeMediumCheckBox.Checked;
				i.width = Int32.Parse(WidthMediumTextBox.Text);
				i.height = Int32.Parse(HeightMediumTextBox.Text);
				i.quality = Int32.Parse(QualityMediumTextBox.Text);
				i.backgroundcolor = Convert.ToInt32(BGColorMediumTextBox.Text, 16);
				coll.SetImageSettings(ImageSize.Medium, i);
				i.fixedsize = FixedSizeThumbCheckBox.Checked;
				i.width = Int32.Parse(WidthThumbTextBox.Text);
				i.height = Int32.Parse(HeightThumbTextBox.Text);
				i.quality = Int32.Parse(QualityThumbTextBox.Text);
				i.backgroundcolor = Convert.ToInt32(BGColorThumbTextBox.Text, 16);
				coll.SetImageSettings(ImageSize.Thumbnail, i);	
				coll.Group = Int32.Parse(CollectionGroupDropDownList.SelectedValue);
				if (coll is RemoteCollection)
				{
					// FogBugz case 551: check input
					props.Set("cachesizelimit", CacheSizeTextBox.Text); 					
					((RemoteCollection)coll).RemoteUrl = RemoteUrlTextBox.Text;
				}
				coll.Update();
				ShowInformation(GetLocalString(this, "CollectionPropertiesUpdated", "Collection properties updated."));
			}
		}

		private void RemoveButton_Click(object sender, System.EventArgs e)
		{
			if (RemoveConfirmationTextBox.Text == GetLocalString(this, "RemoveCollectionConfirmation", "YES"))
			{
				coll.Delete();
				Response.Redirect("collections.aspx"); 
			}
		}

		private void CreateImageButton_Click(object sender, System.EventArgs e)
		{
			ImageIdentifier id = new ImageIdentifier(0, coll.ID);
			Response.Redirect(String.Format("editor.aspx?id={0}&return={1}", 
				id, 
				Server.UrlEncode(String.Format("collection.aspx?id={0}", coll.ID))));
		}

		private void ModerateSubmissionsLinkButton_Click(object sender, System.EventArgs e)
		{
			ImageIdentifier[] result = coll.GetSuggestedImages();
			if (result != null)
			{
				Session["LastSearchResult"] = new ResultPageOptions(
					GetLocalString(this, "SuggestedImages", "Suggested Images"), 
					String.Format("collection.aspx?id={0}", coll.ID), 
					GetLocalString(this, "BackToCollectionProperties", "Back to Collection Properties"), 
					result);
				Response.Redirect("result.aspx"); 
			}
			else
				ShowWarning(GetLocalString(this, "NoImagesAvailableForModeration", "No images available for moderation in this collection."));
		}

	}
}
