using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.ContentManagement.Publishing;
using Microsoft.ContentManagement.Publishing.Extensions.Placeholders;
using Microsoft.ContentManagement.WebControls.Design;
using Microsoft.ContentManagement.WebControls;


namespace ContosoNetControls
{
	/// <summary>
	/// Summary description for CustomProperties.
	/// </summary>
	public class CustomProperties : BasePlaceholderControl
	{
		public CustomProperties()
		{
		}

		#region Presentation Logic

		private Table presentationTable;

		protected override void CreatePresentationChildControls
			(BaseModeContainer presentationContainer)
		{
			Posting thisPosting = CmsHttpContext.Current.Posting;
			presentationTable = new Table();
			presentationTable.BorderWidth = 1;
			presentationTable.BorderColor = System.Drawing.Color.Black;

			foreach (CustomProperty p in thisPosting.CustomProperties)
			{
				AddPropertyForPresentation (presentationTable, p);
			}

			presentationContainer.Controls.Add (presentationTable);
		}

		private void AddPropertyForPresentation (Table table, CustomProperty prop)
		{
			string propName = prop.Name;
			string propValue;
			if (prop.UsesDefaultValue)
			{
				propValue = prop.DefaultValue;
			}
			else
			{
				propValue = prop.Value;
			}

			TableCell nameCell = new TableCell();
			nameCell.Text = propName;
			nameCell.Font.Bold = true;
			nameCell.VerticalAlign = VerticalAlign.Top;
			nameCell.HorizontalAlign = HorizontalAlign.Left;

			TableCell valueCell = new TableCell();
			valueCell.Text = propValue;
			valueCell.VerticalAlign = VerticalAlign.Top;
			valueCell.HorizontalAlign = HorizontalAlign.Left;

			TableRow row = new TableRow();
			row.Cells.Add (nameCell);
			row.Cells.Add (valueCell);
			table.Rows.Add (row);
		}

		protected override void LoadPlaceholderContentForPresentation(PlaceholderControlEventArgs e)
		{
			ViewState ["Test"] = "LoadPreso";
		}


		#endregion

		#region Authoring Logic

		private Table authoringTable;
		protected override void CreateAuthoringChildControls(BaseModeContainer authoringContainer)
		{
			Posting thisPosting = CmsHttpContext.Current.Posting;
			authoringTable = new Table();
			authoringTable.BorderWidth = 1;
			authoringTable.BorderColor = System.Drawing.Color.Black;

			foreach (CustomProperty p in thisPosting.CustomProperties)
			{
				AddPropertyForAuthoring (authoringTable, p);
			}

			authoringContainer.Controls.Add (authoringTable);
		}

		private void AddPropertyForAuthoring (Table table, CustomProperty prop)
		{
			string propName = prop.Name;

			TableCell nameCell = new TableCell();
			nameCell.Text = propName;
			nameCell.Font.Bold = true;
			nameCell.VerticalAlign = VerticalAlign.Top;
			nameCell.HorizontalAlign = HorizontalAlign.Left;

			TableCell valueCell = new TableCell();
			if (prop.AllowedValues.Count > 0)
			{
				DropDownList list = new DropDownList();
				list.ID = "propDDList" + propName;
				list.Width = Unit.Pixel (100);
				
				foreach (string allowedVal in prop.AllowedValues)
				{
					ListItem item = new ListItem(allowedVal, allowedVal);
					list.Items.Add (item);
				}

				valueCell.Controls.Add (list);
			}
			else
			{
				TextBox textbox = new TextBox();
				textbox.ID = "propTextBox" + propName;
				textbox.Width = Unit.Pixel (100);
				valueCell.Controls.Add (textbox);
			}
			valueCell.VerticalAlign = VerticalAlign.Top;
			valueCell.HorizontalAlign = HorizontalAlign.Left;

			TableRow row = new TableRow();
			row.Cells.Add (nameCell);
			row.Cells.Add (valueCell);
			table.Rows.Add (row);
		}

		protected override void LoadPlaceholderContentForAuthoring(PlaceholderControlEventArgs e)
		{
			Posting thisPosting = CmsHttpContext.Current.Posting;
			try
			{
				CmsHttpContext.Current.Posting.CustomProperties["Location"].Value = "Utopia";
			}
			catch (Exception ex)
			{
				string error= ex.Message;
			}

			
			int rowIndex = 0;

			foreach (CustomProperty prop in thisPosting.CustomProperties)
			{
				string propVal = prop.Value;
				TableCell cell = authoringTable.Rows[rowIndex].Cells[1];

				if (prop.AllowedValues.Count > 0)
				{
					// There are specific allowed values - so fill in the drop down list
					DropDownList list = cell.Controls[0] as DropDownList;
					if (list == null)
					{
						throw new Exception ("Invalid control for custom property");
					}
					bool foundItem = false;
					int itemIndex = 0;
					foreach (ListItem item in list.Items)
					{
						if (item.Value == propVal)
						{
							foundItem = true;
							list.SelectedIndex = itemIndex;
						}
						itemIndex++;
					}
					if (!foundItem)
					{
						throw new Exception ("Value of " + prop.Name + " not in allowed list");
					}
				}
				else
				{
					// There are no specific allowed values - we expect a text box
					TextBox tb = cell.Controls[0] as TextBox;
					if (tb == null)
					{
						throw new Exception ("Invalid control for custom property");
					}
					tb.Text = propVal;
				}
				rowIndex++;
			}
		}

		protected override void SavePlaceholderContent(PlaceholderControlSaveEventArgs e)
		{
			Posting thisPosting = CmsHttpContext.Current.Posting;
			ViewState ["Saved"] = "Suppose I put the saved content HERE";
			int rowIndex = 0;

			foreach (CustomProperty prop in thisPosting.CustomProperties)
			{
				string propVal;
				TableCell cell = authoringTable.Rows[rowIndex].Cells[1];

				if (prop.AllowedValues.Count > 0)
				{
					// There are specific allowed values - so fill in the drop down list
					DropDownList list = cell.Controls[0] as DropDownList;
					if (list == null)
					{
						throw new Exception ("Invalid control for custom property");
					}
					propVal = list.SelectedValue;
				}
				else
				{
					// There are no specific allowed values - we expect a text box
					TextBox tb = cell.Controls[0] as TextBox;
					if (tb == null)
					{
						throw new Exception ("Invalid control for custom property");
					}
					propVal = tb.Text;
				}

				prop.Value = propVal;
				rowIndex++;
			}
			
			// All values have been updated - commit!
			CmsHttpContext.Current.CommitAll();
		}

		protected override void OnPopulatingDefaultContent(PlaceholderControlCancelEventArgs e)
		{
			base.OnPopulatingDefaultContent (e);
			Posting thisPosting = CmsHttpContext.Current.Posting;
			int rowIndex = 0;

			foreach (CustomProperty prop in thisPosting.CustomProperties)
			{
				string propDefault = prop.DefaultValue;
				TableCell cell = authoringTable.Rows[rowIndex].Cells[1];

				if (prop.AllowedValues.Count > 0)
				{
					// There are specific allowed values - so fill in the drop down list
					DropDownList list = cell.Controls[0] as DropDownList;
					if (list == null)
					{
						throw new Exception ("Invalid control for custom property");
					}
					bool foundItem = false;
					int itemIndex = 0;
					foreach (ListItem item in list.Items)
					{
						if (item.Value == propDefault)
						{
							foundItem = true;
							list.SelectedIndex = itemIndex;
						}
						itemIndex++;
					}
					if (!foundItem)
					{
						throw new Exception ("Internal exception processing default for " + prop.Name);
					}
				}
				else
				{
					// There are no specific allowed values - we expect a text box
					TextBox tb = cell.Controls[0] as TextBox;
					if (tb == null)
					{
						throw new Exception ("Invalid control for custom property");
					}
					tb.Text = propDefault;
				}
				rowIndex++;
			}
		}

		#endregion
	}
}
