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 MoveImage : PageTemplate.OrciidPage
	{
		private ImageIdentifier id;
		private Orciid.Core.Image image = null;
		private string returnurl;
		private string doneurl;
		protected System.Web.UI.WebControls.HyperLink ReturnHyperLink;
		protected System.Web.UI.WebControls.Button MoveImageButton;
		protected System.Web.UI.WebControls.Button CancelButton;
		protected System.Web.UI.WebControls.Repeater FieldRepeater;
		protected System.Web.UI.WebControls.Label CurrentCollectionLabel;
		protected System.Web.UI.WebControls.Label TargetCollectionLabel;
		private Collection coll = null;
		private int targetcid = 0;
		protected System.Web.UI.WebControls.Label ResourceLabel;
		private Collection targetcoll = null;
		protected System.Web.UI.WebControls.TextBox ResourceTextBox;
		protected System.Web.UI.HtmlControls.HtmlGenericControl Heading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl MoveImageFromLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl MoveImageToLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlTableCell AvailableFieldDataColumnHeader;
		protected System.Web.UI.HtmlControls.HtmlTableCell MapToColumnHeader;
		protected System.Web.UI.HtmlControls.HtmlTableCell ResourceLabelCell;
		protected System.Web.UI.HtmlControls.HtmlGenericControl NewResourceLabelSpan;
		ArrayList sourcevalues = null;

		private void LoadImage()
		{
			if (image != null)
				return;
			id = ImageIdentifier.Parse(Request.QueryString["id"]);
			image = Orciid.Core.Image.GetByID(id);
			coll = Collection.GetByID(image.ID.CollectionID);
			targetcid = Int32.Parse(Request.QueryString["target"]);
			targetcoll = Collection.GetByID(targetcid);
		}
		
		private void Page_Load(object sender, System.EventArgs e)
		{
			if (!IsPostBack)
			{
				returnurl = Request.QueryString["return"];
				if (returnurl != null)
				{
					ReturnHyperLink.Visible = true;
					ReturnHyperLink.NavigateUrl = returnurl;
				}
				else
					ReturnHyperLink.Visible = false;
				doneurl = Request.QueryString["done"];
				if (doneurl == null)
					doneurl = "collections.aspx";
				LoadImage();					
				CurrentCollectionLabel.Text = coll.Title;
				TargetCollectionLabel.Text = targetcoll.Title;
				ResourceLabel.Text = image.Resource;
				sourcevalues = new ArrayList();
				foreach (Field field in coll.GetFields())
				{
					FieldData data = image[field];
					for (int i = 0; i < data.Count; i++)
						sourcevalues.Add(String.Format("{0}:{1}", field.ID, i));
				}
				FieldRepeater.DataSource = sourcevalues;
				FieldRepeater.DataBind();
			}		
		}

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

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

		protected override bool CheckUserPrivileges(Orciid.Core.User user)
		{
			if (user == null)
				return false;
			LoadImage();
			return (coll != null && image != null && image.UserID == 0 && 
					Orciid.Core.User.HasPrivilege(Privilege.ModifyImages, coll, user));
		}

		#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.MoveImageButton.Click += new System.EventHandler(this.MoveImageButton_Click);
			this.CancelButton.Click += new System.EventHandler(this.CancelButton_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void CancelButton_Click(object sender, System.EventArgs e)
		{
			if (returnurl != null)
				Response.Redirect(returnurl);
			else if (doneurl != null)
				Response.Redirect(doneurl);
			else
				Response.Redirect("collections.aspx");
		}

		private void MoveImageButton_Click(object sender, System.EventArgs e)
		{
			Orciid.Core.Image newimage = targetcoll.CreateImage(false);
			if (ResourceTextBox.Text.Length > 0)
				newimage.Resource = ResourceTextBox.Text;

			for (int i = 0; i < sourcevalues.Count; i++)
			{
				string[] f = ((string)sourcevalues[i]).Split(':');
				int fieldid = Int32.Parse(f[0]);
				int instance = Int32.Parse(f[1]);
				RepeaterItem item = FieldRepeater.Items[i];
				DropDownList dropdownlist = item.FindControl("tf") as DropDownList;
				int targetfieldid = Int32.Parse(dropdownlist.SelectedValue);
				if (targetfieldid > 0)
				{
					Field sourcefield = coll.GetField(fieldid);
					Field targetfield = targetcoll.GetField(targetfieldid);
					if (sourcefield.Type == FieldType.Date && targetfield.Type == FieldType.Date)
					{
						FieldDataDate targetdate = (FieldDataDate)newimage[targetfieldid];
						FieldDataDate sourcedate = (FieldDataDate)image[fieldid];
						targetdate.Add(sourcedate[instance], sourcedate.GetOriginalValue(instance),
							sourcedate.GetStartDate(instance), sourcedate.GetEndDate(instance));
					}
					else
						newimage[targetfieldid].Add(image[fieldid][instance]);
				}
			}
			if (coll.MoveImageTo(image, newimage))
				Response.Redirect(String.Format("editor.aspx?id={0}&return={1}",
					newimage.ID, Server.UrlEncode(doneurl)));
			else
			{
				ShowError(GetLocalString(this, "MoveImageFailed", 
					"Moving image failed, please try again or select another target collection."));
				ShowInformation(GetLocalString(this, "MoveImageFailedInfo",
					"Ask your system administrator to check the log for a detailed error message."));
			}
		}

		protected void DataBindFieldLabel(object sender, System.EventArgs e)
		{
			Label label = sender as Label;
			RepeaterItem item = label.Parent as RepeaterItem;
			string[] f = ((string)item.DataItem).Split(':');
			Field field = coll.GetField(Int32.Parse(f[0]));
			label.Text = field.Label;
		}

		protected void DataBindDataLabel(object sender, System.EventArgs e)
		{
			Label label = sender as Label;
			RepeaterItem item = label.Parent as RepeaterItem;
			string[] f = ((string)item.DataItem).Split(':');
			int fieldid = Int32.Parse(f[0]);
			int instance = Int32.Parse(f[1]);
			label.Text = image[fieldid][instance];
		}

		protected void DataBindTargetDropDownList(object sender, System.EventArgs e)
		{
			DropDownList dropdownlist = sender as DropDownList;
			RepeaterItem item = dropdownlist.Parent as RepeaterItem;
			string[] f = ((string)item.DataItem).Split(':');
			Field field = coll.GetField(Int32.Parse(f[0]));
			dropdownlist.Items.Clear();
			dropdownlist.Items.Add(new ListItem(GetLocalString(this, "NoField", "[none]"), "0"));
			int dcrefmatch = 0;
			int dcmatch = 0;
			int namematch = 0;
			int labelmatch = 0;
			foreach (Field tf in targetcoll.GetFields())
			{
				dropdownlist.Items.Add(new ListItem(tf.Label, tf.ID.ToString()));
				if (dcrefmatch == 0)
				{
					if (String.Compare(tf.DCName, field.DCName, true) == 0)
						dcrefmatch = tf.ID;
					else if (dcmatch == 0)
					{
						if (String.Compare(tf.DCElement, field.DCElement, true) == 0)
							dcmatch = tf.ID;
						else if (namematch == 0)
						{
							if (String.Compare(tf.Name, field.Name, true) == 0)
								namematch = tf.ID;
							else if (labelmatch == 0 && 
								String.Compare(tf.Label, field.Label, true) == 0) 
								labelmatch = tf.ID;
						}
					}
				}
			}
			if (dcrefmatch != 0)
				dropdownlist.SelectedValue = dcrefmatch.ToString();
			else if (dcmatch != 0)
				dropdownlist.SelectedValue = dcmatch.ToString();
			else if (namematch != 0)
				dropdownlist.SelectedValue = namematch.ToString();
			else if (labelmatch != 0)
				dropdownlist.SelectedValue = labelmatch.ToString();
			else
				dropdownlist.SelectedValue = "0";
		}

	}
}
