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 Editor : PageTemplate.OrciidPage
	{
		protected System.Web.UI.HtmlControls.HtmlInputFile FileUpload;
		protected System.Web.UI.WebControls.Button CommitButton;
		protected System.Web.UI.WebControls.Button DiscardButton;
		protected Orciid.UserControls.ImageRecordEditor RecordEditor;
		protected System.Web.UI.WebControls.Label MaxHeightLabel;
		protected System.Web.UI.WebControls.Label MaxWidthLabel;
		protected System.Web.UI.WebControls.Panel ImageNavigationPanel;
		protected System.Web.UI.WebControls.DropDownList FieldDropDownList;

		private ImageIdentifier id;
		private Orciid.Core.Image image = null;
		private string returnurl;
		protected System.Web.UI.WebControls.DropDownList MoveDropDownList;
		protected System.Web.UI.WebControls.Button MoveButton;
		protected System.Web.UI.HtmlControls.HtmlGenericControl Heading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl NavigateByLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl UploadFileLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl MaximumSizeLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl MaximumSize2LabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl MaximumSize3LabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl MoveImageLabelSpan;
		protected System.Web.UI.WebControls.Button DiscardButton2;
		protected System.Web.UI.WebControls.Button CommitButton2;
		protected System.Web.UI.WebControls.Image ThumbnailImage;
		private Collection coll = null;
		protected System.Web.UI.WebControls.CheckBox SelectImageCheckBox;
		protected System.Web.UI.WebControls.LinkButton BackLinkButton;
		protected System.Web.UI.WebControls.LinkButton CreateNewImageLinkButton;
		protected System.Web.UI.WebControls.LinkButton PreviousImageLinkButton;
		protected System.Web.UI.WebControls.LinkButton NextImageLinkButton;
		protected System.Web.UI.WebControls.LinkButton DuplicateLinkButton;
		private bool personalimage = false;

		private void LoadImage()
		{
			if (image != null)
				return;
			id = ImageIdentifier.Parse(Request.QueryString["id"]);
			image = Orciid.Core.Image.GetByID(id);
			coll = Collection.GetByID(id.CollectionID);
			personalimage = (Request.QueryString["personal"] == "true");
		}

		private void Page_Load(object sender, System.EventArgs e)
		{
			if (!IsPostBack)
			{
				LoadImage();
				
				returnurl = Request.QueryString["return"];
				BackLinkButton.Visible = (returnurl != null && returnurl.Length > 0);
				
				int navigateby = 0;			
				string nav = Request.QueryString["nav"];
				if (nav != null && nav.Length > 0)
					navigateby = Int32.Parse(Request.QueryString["nav"]);
				if (image != null)
					RecordEditor.DataSource = image;
				else
				{
					RecordEditor.DataSource = coll;
					RecordEditor.PersonalImage = personalimage;
				}
				RecordEditor.DataBind();				
				ImageSettings imgsettings = coll.GetImageSettings(ImageSize.Full);
				MaxHeightLabel.Text = imgsettings.height.ToString();
				MaxWidthLabel.Text = imgsettings.width.ToString();
				FieldDropDownList.Items.Clear();
				foreach (Field f in	coll.GetFields())
				{
					ListItem item = new ListItem(f.Label, f.ID.ToString());
					if (f.ID == navigateby)
						item.Selected = true;
					FieldDropDownList.Items.Add(item);
				}
				UpdateNavigationPanel();

				if (image != null && image.UserID == 0)
				{
					MoveDropDownList.Items.Clear();
					foreach (Collection c in Collection.GetCollections(CollectionType.Internal))
						if (c.ID != coll.ID && Orciid.Core.User.HasPrivilege(Privilege.ModifyImages, c))
							MoveDropDownList.Items.Add(new ListItem(c.Title, c.ID.ToString()));
					MoveDropDownList.Parent.Visible = (MoveDropDownList.Items.Count > 0);
				}
				else
					MoveDropDownList.Parent.Visible = false;

				if (image != null)
				{
					ArrayList selectedImages = Session["SelectedImages"] as ArrayList;
					if (selectedImages != null)
						SelectImageCheckBox.Checked = (selectedImages.Contains(image.ID));
				}

				if (Request.QueryString["duplicate"] != null)
					ShowInformation(GetLocalString(this, "ImageDuplicated", "The duplicate record has been created and is shown"));
			}
			DisableButtonOnClick(CommitButton, GetLocalString(this, "SavingChanges", "Saving changes..."));
			DisableButtonOnClick(CommitButton2, GetLocalString(this, "SavingChanges", "Saving changes..."));
		}

//		string PreviousImageNavigateUrl = null;
//		string NextImageNavigateUrl = null;

		private void UpdateNavigationPanel()
		{
			if (image != null && coll != null && 
				coll.HasImageNavigation() && FieldDropDownList.Items.Count > 0)
			{
				ImageNavigationPanel.Visible = true;
				int field = Int32.Parse(FieldDropDownList.SelectedValue);
				FieldData data = image[field];
				if (data != null && data.Count > 0)
				{
					PreviousImageLinkButton.Visible = true;
					NextImageLinkButton.Visible = true;

/*					bool iscurator = Orciid.Core.User.HasPrivilege(Privilege.ModifyImages, coll);

					ImageIdentifier prev = coll.GetAdjacentImage(id, field, data[0], false, !iscurator);
					if (prev.ID != 0)
					{
						PreviousImageLinkButton.Visible = true;
						PreviousImageNavigateUrl = String.Format("editor.aspx?id={0}&nav={1}",
							Server.UrlEncode(prev.ToString()), field);
					}
					else
						PreviousImageLinkButton.Visible = false;

					ImageIdentifier next = coll.GetAdjacentImage(id, field, data[0], true, !iscurator);
					if (next.ID != 0)
					{
						NextImageLinkButton.Visible = true;
						NextImageNavigateUrl = String.Format("editor.aspx?id={0}&nav={1}",
							Server.UrlEncode(next.ToString()), field);
					}
					else
						NextImageLinkButton.Visible = false;
*/				}
				else
				{
					PreviousImageLinkButton.Visible = false;
					NextImageLinkButton.Visible = false;
				}
			}
			else
				ImageNavigationPanel.Visible = false;
		}

		protected override void LoadViewState(object savedState) 
		{
			if (savedState != null)
			{
				base.LoadViewState(savedState);
				if (ViewState["returnurl"] is String)
					returnurl = (string)ViewState["returnurl"];
				if (ViewState["id"] is ImageIdentifier)
				{
					id = (ImageIdentifier)ViewState["id"];
					image = Orciid.Core.Image.GetByID(id);
					coll = Collection.GetByID(id.CollectionID);
				}
			}
		}

		protected override object SaveViewState()
		{
			ViewState["returnurl"] = returnurl;
			ViewState["id"] = id;
			return base.SaveViewState();
		}

		protected override bool CheckUserPrivileges(Orciid.Core.User user)
		{
			if (user == null)
				return false;
			LoadImage();
			if (coll == null)
				return false;
			if (image == null)
			{
				// creating new image
				if (personalimage)
					return Orciid.Core.User.HasPrivilege(Privilege.PersonalImages, coll, user);
				else
					return Orciid.Core.User.HasPrivilege(Privilege.ModifyImages, coll, user);
			}
			else
			{
				// editing existing image
				if (image.UserID == 0)
					return Orciid.Core.User.HasPrivilege(Privilege.ModifyImages, coll, user);
				if (image.UserID == user.ID)
					return Orciid.Core.User.HasPrivilege(Privilege.PersonalImages, coll, user);
				return false;
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			Orciid.Core.User user = Session["CurrentUser"] as Orciid.Core.User;
			if (user != null)
				user.Activate(Request.UserHostAddress);	

			//
			// 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.BackLinkButton.Click += new System.EventHandler(this.BackLinkButton_Click);
			this.CreateNewImageLinkButton.Click += new System.EventHandler(this.CreateNewImageLinkButton_Click);
			this.FieldDropDownList.SelectedIndexChanged += new System.EventHandler(this.FieldDropDownList_SelectedIndexChanged);
			this.PreviousImageLinkButton.Click += new System.EventHandler(this.PreviousImageLinkButton_Click);
			this.NextImageLinkButton.Click += new System.EventHandler(this.NextImageLinkButton_Click);
			this.CommitButton.Click += new System.EventHandler(this.CommitButton_Click);
			this.DiscardButton.Click += new System.EventHandler(this.DiscardButton_Click);
			this.SelectImageCheckBox.CheckedChanged += new System.EventHandler(this.SelectImageCheckBox_CheckedChanged);
			this.CommitButton2.Click += new System.EventHandler(this.CommitButton_Click);
			this.DiscardButton2.Click += new System.EventHandler(this.DiscardButton_Click);
			this.MoveButton.Click += new System.EventHandler(this.MoveButton_Click);
			this.DuplicateLinkButton.Click += new System.EventHandler(this.DuplicateLinkButton_Click);
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Editor_PreRender);

		}
		#endregion

		private void CommitButton_Click(object sender, System.EventArgs e)
		{
			RecordEditor.CommitData();
			if (RecordEditor.DataSource is Orciid.Core.Image)
				id = ((Orciid.Core.Image)RecordEditor.DataSource).ID;
			if (id.CollectionID != 0 && 
				id.ID != 0)
				image = Orciid.Core.Image.GetByID(id);
			if (id.CollectionID != 0 && 
				id.ID != 0 &&
				image != null &&
				FileUpload.PostedFile != null &&
				FileUpload.PostedFile.InputStream != null &&
				FileUpload.PostedFile.ContentLength > 0)
			{
				try
				{
//					image = Orciid.Core.Image.GetByID(id);
					if (!image.SetResourceData(FileUpload.PostedFile.InputStream, FileUpload.PostedFile.ContentType))
						throw new Exception("Could not set resource data.");
					// SetResourceData may have updated the image's Resource, so reload
					RecordEditor.DataSource = image;
					RecordEditor.DataBind();
				}
				catch
				{
					ShowError(GetLocalString(this, "CouldNotProcess", "The image you tried to upload could not be processed."));
					return;
				}
			}
			ShowInformation(GetLocalString(this, "ChangesSaved", "Changes have been saved."));

			// check if selection box is checked for this potentially newly created image
			SelectImageCheckBox_CheckedChanged(null, null);

			UpdateNavigationPanel();
		}

		private void DiscardButton_Click(object sender, System.EventArgs e)
		{
//			if (returnurl != null)
//				Response.Redirect(returnurl);
			if (image != null)
				RecordEditor.DataSource = image;
			else
				RecordEditor.DataSource = coll;
			RecordEditor.DataBind();
		}

		private void FieldDropDownList_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			UpdateNavigationPanel();
		}

		private void MoveButton_Click(object sender, System.EventArgs e)
		{
			Response.Redirect(String.Format("moveimage.aspx?id={0}&return={1}&done={2}&target={3}",
				image.ID,
				Server.UrlEncode(String.Format("editor.aspx?id={0}&return={1}&nav={2}", 
					image.ID, Server.UrlEncode(returnurl), Server.UrlEncode(Request.QueryString["nav"]))), 
				Server.UrlEncode(returnurl),
				MoveDropDownList.SelectedValue));
		}

		private void Editor_PreRender(object sender, System.EventArgs e)
		{
			if (image != null)
			{
				ThumbnailImage.ImageUrl =
					String.Format("getimage.aspx?cid={0}&res={1}&format=T&x={2}", 
					image.ID.CollectionID, 
					HttpUtility.UrlEncode(image.Resource), 
					DateTime.Now.Ticks // to keep the browser from showing a cached version
					);
				ThumbnailImage.Visible = true;

				ArrayList selectedImages = Session["SelectedImages"] as ArrayList;
				SelectImageCheckBox.Checked =
					(selectedImages != null && selectedImages.Contains(image.ID));

				DuplicateLinkButton.Visible = true;
			}
			else
			{
				ThumbnailImage.Visible = false;
				DuplicateLinkButton.Visible = false;
			}
		}

		private void SelectImageCheckBox_CheckedChanged(object sender, System.EventArgs e)
		{
			if (image == null || image.ID.CollectionID == 0 || image.ID.ID == 0)
				return;
			ArrayList selectedImages = Session["SelectedImages"] as ArrayList;
			if (selectedImages == null)
				selectedImages = new ArrayList();
			bool waschecked = selectedImages.Contains(image.ID);
			if (SelectImageCheckBox.Checked && !waschecked)
				selectedImages.Add(image.ID);
			if (!SelectImageCheckBox.Checked && waschecked)
				selectedImages.Remove(image.ID);
			Session["SelectedImages"] = selectedImages;
		}

		private void BackLinkButton_Click(object sender, System.EventArgs e)
		{
			Response.Redirect(returnurl);
		}

		private void CreateNewImageLinkButton_Click(object sender, System.EventArgs e)
		{
			Response.Redirect(String.Format(
				"editor.aspx?id={0}&return={1}&personal={2}",
				new ImageIdentifier(0, coll.ID),
				returnurl == null ? "" : Server.UrlEncode(returnurl),
				personalimage || (image != null && image.UserID != 0) ? "true" : "false"));
		}

		private void PreviousImageLinkButton_Click(object sender, System.EventArgs e)
		{
			//UpdateNavigationPanel();
			//if (PreviousImageNavigateUrl != null)
			//	Response.Redirect(PreviousImageNavigateUrl);	

			int field = Int32.Parse(FieldDropDownList.SelectedValue);
			FieldData data = image[field];
			if (data != null && data.Count > 0)
			{
				bool iscurator = Orciid.Core.User.HasPrivilege(Privilege.ModifyImages, coll);
				ImageIdentifier prev = coll.GetAdjacentImage(id, field, data[0], false, !iscurator);
				if (prev.ID != 0)
				{
					Response.Redirect(String.Format("editor.aspx?id={0}&nav={1}",
						Server.UrlEncode(prev.ToString()), field));
				}
				else
					ShowInformation(GetLocalString(this, "NoMorePrev", "There are no images preceding the one you are editing."));
			}
		}

		private void NextImageLinkButton_Click(object sender, System.EventArgs e)
		{
			//UpdateNavigationPanel();
			//if (NextImageNavigateUrl != null)
			//	Response.Redirect(NextImageNavigateUrl);

			int field = Int32.Parse(FieldDropDownList.SelectedValue);
			FieldData data = image[field];
			if (data != null && data.Count > 0)
			{
				bool iscurator = Orciid.Core.User.HasPrivilege(Privilege.ModifyImages, coll);
				ImageIdentifier next = coll.GetAdjacentImage(id, field, data[0], true, !iscurator);
				if (next.ID != 0)
				{
					Response.Redirect(String.Format("editor.aspx?id={0}&nav={1}",
						Server.UrlEncode(next.ToString()), field));
					}
				else
					ShowInformation(GetLocalString(this, "NoMoreNext", "There are no images following the one you are editing."));
			}
		}

		private void DuplicateLinkButton_Click(object sender, System.EventArgs e)
		{
			if (image == null)
				return;

			Orciid.Core.Image dupimg = image.Duplicate();
			dupimg.Update();
			
			Response.Redirect(String.Format(
				"editor.aspx?id={0}&personal={1}&duplicate=1",
				dupimg.ID,
				personalimage || (image != null && image.UserID != 0) ? "true" : "false"));
		}
	}
}
