namespace Orciid.UserControls
{
	using System;
	using System.Collections;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;
	using Orciid.Core;

	public class FieldMappingControl : System.Web.UI.UserControl
	{
		protected System.Web.UI.WebControls.DataGrid FieldDataGrid;

		private FieldMapping fieldmapping = null;
		private Hashtable fielddata = null;

		public FieldMapping FieldMapping
		{
			get
			{
				return fieldmapping;
			}
			set
			{
				fieldmapping = value;
			}
		}

		public Hashtable FieldData
		{
			set
			{
				fielddata = value;
			}
		}

		private void Page_Load(object sender, System.EventArgs e)
		{
			if (IsPostBack)
			{
				foreach (DataGridItem item in FieldDataGrid.Items)
				{
					string source = item.Cells[0].Text;
					string target = ((DropDownList)item.Cells[2].FindControl("t")).SelectedValue;
					fieldmapping.AddMapping(source, target);
				}
			}
		}

		public override void DataBind()
		{
			if (fieldmapping == null)
				return;

			DataTable table = new DataTable();
			table.Columns.Add("SourceField");
			table.Columns.Add("FieldData");
			table.Columns.Add("TargetField");

			foreach (string s in fieldmapping.SourceFields)
			{
				table.Rows.Add(new object[] {
												s, 
												fielddata != null ? (string)fielddata[s] : null,
												fieldmapping.GetMapping(s) 
											});
			}			

			FieldDataGrid.DataSource = table;
			FieldDataGrid.DataBind();

			FieldDataGrid.Columns[1].Visible = (fielddata != null);
		}


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

		}
		#endregion

		protected void DataBindTargetFieldDropDownList(object sender, System.EventArgs e)
		{
			DropDownList dropdownlist = sender as DropDownList;
			DataGridItem item = dropdownlist.Parent.Parent as DataGridItem;
			DataRowView row = item.DataItem as DataRowView;
			dropdownlist.Items.Clear();			
			dropdownlist.Items.Add(new ListItem("", ""));
			foreach (string s in fieldmapping.TargetFields)
			{
				ListItem li = new ListItem(s);
				string targetfield = row["TargetField"] as String;
				li.Selected = (targetfield != null && s == targetfield);
				dropdownlist.Items.Add(li);
			}
		}

		protected override void LoadViewState(object savedState) 
		{
			if (savedState != null)
			{
				base.LoadViewState(savedState);
				fieldmapping = (FieldMapping)ViewState["fm"];
			}
		}

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

	}
}
