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 controlledlists : PageTemplate.OrciidPage
	{
		protected System.Web.UI.WebControls.Label CollectionTitleLabel;
		protected System.Web.UI.WebControls.Button ModifyButton;
		protected System.Web.UI.WebControls.Button RemoveButton;
		protected System.Web.UI.WebControls.Button CreateButton;
		protected System.Web.UI.WebControls.Panel ModifyPanel;
		protected System.Web.UI.WebControls.TextBox NewEntriesTextBox;
		protected System.Web.UI.WebControls.Button AddNewEntriesButton;
		protected System.Web.UI.WebControls.ListBox RemoveEntriesListBox;
		protected System.Web.UI.WebControls.Button RemoveEntriesButton;
		protected System.Web.UI.WebControls.DropDownList RenameEntryDropDownList;
		protected System.Web.UI.WebControls.TextBox NewEntryNameTextBox;
		protected System.Web.UI.WebControls.Button RenameEntryButton;
		protected System.Web.UI.WebControls.DropDownList MergeEntryDropDownList;
		protected System.Web.UI.WebControls.DropDownList MergeTargetDropDownList;
		protected System.Web.UI.WebControls.Button MergeEntriesButton;
		protected System.Web.UI.WebControls.HyperLink PropertiesHyperLink;
		protected System.Web.UI.WebControls.ListBox ControlledListsListBox;
		protected System.Web.UI.WebControls.Label ControlledListTitleLabel;
	
		private Collection coll;
		protected System.Web.UI.WebControls.Button UpdateButton;
		protected System.Web.UI.WebControls.TextBox DescriptionTextBox;
		protected System.Web.UI.WebControls.TextBox OriginTextBox;
		protected System.Web.UI.WebControls.CheckBox StandardCheckBox;
		protected System.Web.UI.WebControls.TextBox TitleTextBox;
		protected System.Web.UI.HtmlControls.HtmlGenericControl Heading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl TitleLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl DescriptionLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl OriginLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl AddNewEntriesLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl OnePerLineLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl RemoveEntriesLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl RenameEntryLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl RenameEntryToLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl MergeEntryLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl MergeEntryWithLabelSpan;
		private ControlledList list;

		private void Page_Load(object sender, System.EventArgs e)
		{
			if (!IsPostBack)
			{
				try
				{
					coll = Collection.GetByID(Int32.Parse(Request.QueryString["id"]));
				}
				catch
				{
					coll = null;
				}
				CheckAuthorization();
				PopulateControlledListsListBox();
				PropertiesHyperLink.NavigateUrl = String.Format("collection.aspx?id={0}", coll.ID);
			}
		}

		private void PopulateControlledListsListBox()
		{
			ControlledListsListBox.Items.Clear();
			foreach (ControlledList list in ControlledList.GetControlledLists(coll.ID))
				ControlledListsListBox.Items.Add(new ListItem(list.Title, list.ID.ToString()));
		}

		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"]);
				if (ViewState["clid"] != null)
				{
					int id = (int)ViewState["clid"];
					if (id != 0)
						list = ControlledList.GetByID(id);
					else
						list = new ControlledList();
				}
				CheckAuthorization();
			}
		}

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

		private void CheckAuthorization()
		{
			Privilege[] privs = new Privilege[] { Privilege.ManageControlledLists };
			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.ModifyButton.Click += new System.EventHandler(this.ModifyButton_Click);
			this.RemoveButton.Click += new System.EventHandler(this.RemoveButton_Click);
			this.CreateButton.Click += new System.EventHandler(this.CreateButton_Click);
			this.UpdateButton.Click += new System.EventHandler(this.UpdateButton_Click);
			this.AddNewEntriesButton.Click += new System.EventHandler(this.AddNewEntriesButton_Click);
			this.RemoveEntriesButton.Click += new System.EventHandler(this.RemoveEntriesButton_Click);
			this.RenameEntryButton.Click += new System.EventHandler(this.RenameEntryButton_Click);
			this.MergeEntriesButton.Click += new System.EventHandler(this.MergeEntriesButton_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 ModifyButton_Click(object sender, System.EventArgs e)
		{
			if (ControlledListsListBox.SelectedValue != null && ControlledListsListBox.SelectedValue.Length > 0)
			{
				list = ControlledList.GetByID(Int32.Parse(ControlledListsListBox.SelectedValue));
				ShowModifyPanel();
			}
		}

		private void PopulateLists()
		{
			RemoveEntriesListBox.Items.Clear();
			RenameEntryDropDownList.Items.Clear();
			MergeEntryDropDownList.Items.Clear();
			MergeTargetDropDownList.Items.Clear();
			foreach (DictionaryEntry item in list.GetSortedList())
			{
				string k = item.Key.ToString();
				string v = item.Value.ToString();
				RemoveEntriesListBox.Items.Add(new ListItem(k, v));
				RenameEntryDropDownList.Items.Add(new ListItem(k, v));
				MergeEntryDropDownList.Items.Add(new ListItem(k, v));
				MergeTargetDropDownList.Items.Add(new ListItem(k, v));				
			}
		}

		private void RemoveButton_Click(object sender, System.EventArgs e)
		{
			ModifyPanel.Visible = false;
			if (ControlledListsListBox.SelectedValue != null && ControlledListsListBox.SelectedValue.Length > 0)
			{
				list = ControlledList.GetByID(Int32.Parse(ControlledListsListBox.SelectedValue));
				try
				{
					list.Delete();
					PopulateControlledListsListBox();
				}
				catch (CoreException ex)
				{
					ShowError(ex.Message);
				}
			}
		}

		private void CreateButton_Click(object sender, System.EventArgs e)
		{
			list = new ControlledList();
			ShowModifyPanel();
		}

		private void ShowModifyPanel()
		{
			if (list == null)
			{
				ModifyPanel.Visible = false;
				return;
			}
			ModifyPanel.Visible = true;
			PopulateLists();
			NewEntryNameTextBox.Text = "";
			TitleTextBox.Text = list.Title;
			DescriptionTextBox.Text = list.Description;
			OriginTextBox.Text = list.Origin;
			StandardCheckBox.Checked = list.Standard;
			ControlledListTitleLabel.Text = list.Title;
		}

		private void UpdateButton_Click(object sender, System.EventArgs e)
		{
			try
			{
				list.Title = TitleTextBox.Text;
				list.Description = DescriptionTextBox.Text;
				list.Origin = OriginTextBox.Text;
				list.Standard = StandardCheckBox.Checked;
				list.CollectionID = coll.ID;
				list.Update();
				PopulateControlledListsListBox();
				ShowModifyPanel();
			}
			catch (CoreException ex)
			{
				ShowError(ex.Message);
			}
		}

		private void AddNewEntriesButton_Click(object sender, System.EventArgs e)
		{
			if (list != null && NewEntriesTextBox.Text != null && NewEntriesTextBox.Text.Length > 0)
			{
				// if list is newly created, simulate an Update button click as well
				if (list.ID == 0)
					UpdateButton_Click(sender, e);
				string[] entries = NewEntriesTextBox.Text.Split(new char[] { '\n' });
				for (int i = 0; i < entries.Length; i++)
					entries[i] = entries[i].Trim();
				list.Add(entries);
				NewEntriesTextBox.Text = "";
				PopulateLists();
			}
		}

		private void RemoveEntriesButton_Click(object sender, System.EventArgs e)
		{
			if (list != null)
			{
				ArrayList ids = new ArrayList();
				foreach (ListItem item in RemoveEntriesListBox.Items)
					if (item.Selected)
						ids.Add(Int32.Parse(item.Value));
				list.Remove((int[])ids.ToArray(typeof(int)));
				PopulateLists();
			}
		}

		private void RenameEntryButton_Click(object sender, System.EventArgs e)
		{
			if (list != null && RenameEntryDropDownList.SelectedValue != null && 
				RenameEntryDropDownList.SelectedValue.Length > 0 && 
				NewEntryNameTextBox.Text != null && NewEntryNameTextBox.Text.Length > 0)
			{
				int id = Int32.Parse(RenameEntryDropDownList.SelectedValue);
				try
				{
					list.Rename(id, NewEntryNameTextBox.Text);
					PopulateLists();
				}
				catch (CoreException ex)
				{
					ShowError(ex.Message);
				}
			}
		}

		private void MergeEntriesButton_Click(object sender, System.EventArgs e)
		{
			if (list != null && MergeEntryDropDownList.SelectedValue != null && 
				MergeEntryDropDownList.SelectedValue.Length > 0 && 
				MergeTargetDropDownList.SelectedValue != null && 
				MergeTargetDropDownList.SelectedValue.Length > 0)
			{
				int id = Int32.Parse(MergeEntryDropDownList.SelectedValue);
				int tid = Int32.Parse(MergeTargetDropDownList.SelectedValue);
				try
				{
					list.Rename(id, list[tid], true);
					PopulateLists();
				}
				catch (CoreException ex)
				{
					ShowError(ex.Message);
				}
			}
		}
	}
}
