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

	public class UserSelection : System.Web.UI.UserControl
	{
		protected System.Web.UI.WebControls.DataGrid UserDataGrid;
		protected System.Web.UI.WebControls.Repeater FirstLetterRepeater;
		protected bool sortBySurname;

		private Orciid.Core.User[] currentusers = null;
		private int[] datasource = null;
		private ArrayList selected;
		private int[] userids;

		public int[] DataSource
		{
			set
			{
				datasource = value;
			}
		}

		public int[] GetSelection()
		{
			return (int[])selected.ToArray(typeof(int));
		}

		public override void DataBind()
		{
			Trace.Warn("DataBind", "DataBind called and executing. sortBySurname=" + sortBySurname);
		
			base.DataBind();

			string[] patterns = null;
			if (sortBySurname) 
				patterns = Orciid.Core.User.GetNamePatterns(1);
			else
				patterns = Orciid.Core.User.GetLoginPatterns(1);

			FirstLetterRepeater.DataSource = patterns;
			FirstLetterRepeater.DataBind();
			if (patterns != null && patterns.Length > 0)
				QueryUsers(patterns[0]);
			selected = new ArrayList();
			if (datasource != null)
				selected.AddRange(datasource);
			UserDataGrid.CurrentPageIndex = 0;
			BindGrid();
		}

		private void QueryUsers(string filter)
		{
			Trace.Warn("QueryUsers", "QueryUsers called with " + filter + ". sortBySurname=" + sortBySurname);
			
			Orciid.Core.User[] users = null;
			if (sortBySurname)
				users = Orciid.Core.User.GetByNamePattern(filter);
			else
				users = Orciid.Core.User.GetByLoginPattern(filter);

			userids = new int[users.Length];
			for (int i = 0; i < users.Length; i++)
				userids[i] = users[i].ID;
			currentusers = new Orciid.Core.User[Math.Min(UserDataGrid.PageSize, users.Length)];
			for (int i = 0; i < currentusers.Length; i++)
				currentusers[i] = users[i];
		}

		private void BindGrid()
		{
			//Orciid.Core.User user = Orciid.Core.User.CurrentUser();
			Orciid.Core.User[] users;
			
			UserDataGrid.AllowPaging = (userids.Length > UserDataGrid.PageSize);
			UserDataGrid.VirtualItemCount = userids.Length;
			if (currentusers != null)
				users = currentusers;
			else
			{
				int count = (UserDataGrid.CurrentPageIndex < UserDataGrid.PageCount - 1 ?
					UserDataGrid.PageSize : 
					userids.Length - (UserDataGrid.PageCount - 1) * UserDataGrid.PageSize);
				int[] a = new int[count];
				Array.Copy(userids, UserDataGrid.PageSize * UserDataGrid.CurrentPageIndex, a, 0, count);
				users = Orciid.Core.User.GetByID(a);
			}

			if (users.Length == 0)
				UserDataGrid.Visible = false;
			else
			{
				UserDataGrid.Visible = true;
				UserDataGrid.DataSource = users;
				UserDataGrid.DataBind();
			}
		}

		protected override void LoadViewState(object savedState) 
		{
			if (savedState != null)
			{
				base.LoadViewState(savedState);
				selected = ViewState["selected"] as ArrayList;
				userids = (int[])ViewState["userids"];
			}
		}

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

		private void Page_Load(object sender, System.EventArgs e)
		{
			Trace.Warn("Page_Load", "Page Load was called ##########################");
		}

		#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.FirstLetterRepeater.ItemCommand += new System.Web.UI.WebControls.RepeaterCommandEventHandler(this.FirstLetterRepeater_ItemCommand);
			this.UserDataGrid.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.UserDataGrid_PageIndexChanged);
			this.Load += new System.EventHandler(this.Page_Load);
		}
		#endregion

		private void FirstLetterRepeater_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
		{
			QueryUsers((string)e.CommandArgument);
			UserDataGrid.CurrentPageIndex = 0;
			BindGrid();
		}

		private void UserDataGrid_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
		{
			UserDataGrid.CurrentPageIndex = e.NewPageIndex;
			BindGrid();
		}

		private DataGridItem GetDataGridItem(Control control)
		{
			while (!(control is DataGridItem) && control.Parent != null)
				control = control.Parent;
			return control as DataGridItem;
		}

		protected void DataBindSelectCheckBox(object sender, System.EventArgs e)
		{
			if (selected == null)
				return;
			CheckBox control = sender as CheckBox;
			DataGridItem item = GetDataGridItem(control);
			control.Checked = (selected.Contains(((Orciid.Core.User)item.DataItem).ID));
		}

		protected void CheckedChangedSelectedCheckBox(object sender, System.EventArgs e)
		{
			if (selected == null)
				return;
			CheckBox control = sender as CheckBox;
            DataGridItem item = GetDataGridItem(control);
			if (control.Checked)
				selected.Add(userids[item.ItemIndex + UserDataGrid.CurrentPageIndex * UserDataGrid.PageSize]);
			else
				selected.Remove(userids[item.ItemIndex + UserDataGrid.CurrentPageIndex * UserDataGrid.PageSize]);
		}
		
		
		protected void OrderByName_Click(object sender, System.EventArgs e)
		{
			Trace.Warn("Button By Name", "Click event found!");
			sortBySurname = true;
			this.DataBind();
		}

		protected void OrderByLogin_Click(object sender, System.EventArgs e)
		{
			Trace.Warn("Button By Login", "Click event found!");
			sortBySurname = false;
			this.DataBind();
		}
		
	}
}
