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 BrowseForm : PageTemplate.OrciidPage
	{
		protected System.Web.UI.WebControls.DropDownList CollectionList;
		protected System.Web.UI.WebControls.DropDownList FieldList;
		protected System.Web.UI.WebControls.PlaceHolder PatternPlaceHolder;
		protected System.Web.UI.HtmlControls.HtmlGenericControl Heading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl CollectionLabelSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl FieldLabelSpan;
		protected System.Web.UI.WebControls.DataList R;
		protected System.Web.UI.WebControls.Panel TermsPanel;
		protected System.Web.UI.WebControls.HyperLink TermsHyperLink;

		private string[] browsevalues = null;

		private class LastBrowseSettings
		{
			public int collectionid;
			public int fieldid;
			public string startat;
		}

		private void Page_Load(object sender, System.EventArgs e)
		{
			if (!IsPostBack)
			{
				LastBrowseSettings last = Session["LastBrowseSettings"] as LastBrowseSettings;
				string preselect = (last != null ? last.collectionid.ToString() : "");
				if (Request.QueryString["cid"] != null)
					preselect = Request.QueryString["cid"];
				ArrayList colls = new ArrayList();
				foreach (Collection coll in Collection.GetCollections())
					if (coll.IsBrowsable)
						colls.Add(coll);
				colls.Sort();
				CollectionList.DataSource = colls;
				CollectionList.DataTextField = "Title";
				CollectionList.DataValueField = "ID";
				CollectionList.DataBind();
				foreach (ListItem item in CollectionList.Items)
					if (item.Value == preselect)
					{
						item.Selected = true;
						break;
					}
				BindFieldList();	
				if (last != null)
				{
					foreach (ListItem item in FieldList.Items)
						if (item.Value == last.fieldid.ToString())
						{
							item.Selected = true;
							break;
						}
					JumpToValue(last.startat, true, true);
				}
				else
					JumpToValue("A", true, true);
			}

			for (char c = 'A'; c <= 'Z'; c++)
			{
				if (c != 'A')
				{
					HtmlImage image = new HtmlImage();
					image.Src = "images/separator.gif";
					image.Attributes["hspace"] = "2";
					PatternPlaceHolder.Controls.Add(image);
				}
				LinkButton button = new LinkButton();
				button.Text = c.ToString();
				button.Command += new CommandEventHandler(this.PatternButton_ItemCommand);
				button.CommandArgument = c.ToString();
				PatternPlaceHolder.Controls.Add(button);
			}
			HtmlImage image2 = new HtmlImage();
			image2.Src = "images/separator.gif";
			image2.Attributes["hspace"] = "2";
			PatternPlaceHolder.Controls.Add(image2);
			LinkButton button2 = new LinkButton();
			button2.Text = GetLocalString(this, "Other", "Other");
			button2.Command += new CommandEventHandler(this.PatternButton_ItemCommand);
			button2.CommandArgument = " ";
			PatternPlaceHolder.Controls.Add(button2);

			Collection tcoll = Collection.GetByID(Int32.Parse(CollectionList.SelectedValue));
			if (tcoll.Type == CollectionType.Internal)
			{
				TermsHyperLink.NavigateUrl = "terms.aspx?c=" + tcoll.ID.ToString();
				TermsHyperLink.Visible = true;
			}
			else
				TermsHyperLink.Visible = false;
		}

		protected override void LoadViewState(object savedState) 
		{
			if (savedState != null)
			{
				base.LoadViewState(savedState);
				browsevalues = ViewState["browsevalues"] as string[];
			}
		}

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

		private void BindFieldList()
		{
			Collection c;
			try
			{
				c = Collection.GetByID(Int32.Parse(CollectionList.SelectedItem.Value));
			}
			catch
			{
				c = null;
			}
			if (c != null)
			{
				ArrayList a = new ArrayList();
				foreach (Field f in c.GetFields())
					if (f.Browsable)
						a.Add(f);
				FieldList.DataSource = a;
				FieldList.DataTextField = "Label";
				FieldList.DataValueField = "ID";
			}
			else
			{
				FieldList.DataSource = null;
			}
			FieldList.DataBind();
		}

		#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.CollectionList.SelectedIndexChanged += new System.EventHandler(this.CollectionList_SelectedIndexChanged);
			this.FieldList.SelectedIndexChanged += new System.EventHandler(this.FieldList_SelectedIndexChanged);
			this.R.ItemCommand += new System.Web.UI.WebControls.DataListCommandEventHandler(this.R_ItemCommand);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		public override string GetHighlightedMenuItem()
		{
			return "Resources_Browse";
		}

		protected override bool CheckUserPrivileges(Orciid.Core.User user)
		{
			return Orciid.Core.User.HasPrivilegeOnAny('C', user, Privilege.ReadCollection);
		}

		private void PatternButton_ItemCommand(object source, System.Web.UI.WebControls.CommandEventArgs e)
		{
			JumpToValue((string)e.CommandArgument, true, true);
		}

		private void JumpToValue(string s, bool include, bool ascending)
		{
			ClearResultGrid();
			Collection c;
			try
			{
				c = Collection.GetByID(Int32.Parse(CollectionList.SelectedItem.Value));
			}
			catch
			{
				c = null;
			}
			if (c == null)
				return;
			Field f = c.GetField(Int32.Parse(FieldList.SelectedItem.Value));
			if (f == null)
				return;
			string[] b = c.GetBrowseValues(f, s, include, ascending, 100);
			if (b != null)
				browsevalues = b;
			else if (browsevalues != null)
				ShowWarning(GetLocalString(this, "NoMoreTerms", "No more terms found"));
			if (browsevalues != null)
			{
				TermsPanel.Visible = true;
				R.DataSource = browsevalues;
				R.DataBind();
				SaveBrowseSettings();
			}
		}
		
		private void R_ItemCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e)
		{
			if (e.CommandName == "BrowseResult")
			{
				string term = Server.HtmlDecode(((LinkButton)e.CommandSource).Text);
				Search.SearchParameters parameters = new Search.SearchParameters();
				
				Collection c = Collection.GetByID(Int32.Parse(CollectionList.SelectedItem.Value));
				if (c == null)
					return;
				parameters.collections.Add(c);
				SearchField s = new SearchField();
				Field f = c.GetField(Int32.Parse(FieldList.SelectedItem.Value));
				if (f == null)
					return;
				s.Name = f.Name;
				ExactTextCondition cond = new ExactTextCondition();
				cond.Keyword = term;
				cond.Field = s;
				parameters.conditions.Add(cond);
					
				try
				{
					ImageIdentifier[] images = Search.Execute(parameters, Configuration.Instance.GetInt("ui.maxsearchresults"), false);
					if (images == null || images.Length == 0)
						parameters.warnings.Add(GetLocalString(this, "NoImagesFound",
							"No matching image records were found."));
					else
						Session["LastSearchResult"] = new ResultPageOptions(
							GetLocalString(this, "BrowseResults", "Browse Results"), 
							"browse.aspx", 
							GetLocalString(this, "BackToBrowse", "Back to Browse"), 
							images);
				}
				catch (TooManySearchResultsException)
				{
					parameters.warnings.Add(GetLocalString(this, "TooManyImages", 
						"Too many images match this browse term. " +
						"Please select another term or perform a search instead."));
				}
				if (parameters.warnings.Count == 0)
				{				
					Response.Redirect("result.aspx"); 
				}
				else
				{
					foreach (string sw in parameters.warnings)
						ShowWarning(sw);
				}
			} 
			else if (e.CommandName == "PreviousTerms")
			{
				JumpToValue(browsevalues[0], false, false);
			}
			else if (e.CommandName == "NextTerms")
			{
				JumpToValue(browsevalues[browsevalues.Length - 1], false, true);
			}
		}

		private void SaveBrowseSettings()
		{
			LastBrowseSettings last = new LastBrowseSettings();
			last.collectionid = Int32.Parse(CollectionList.SelectedItem.Value);
			last.fieldid = Int32.Parse(FieldList.SelectedItem.Value);
			last.startat = browsevalues[0];
			Session["LastBrowseSettings"] = last;
		}

		private void CollectionList_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			BindFieldList();
//			ClearResultGrid();
			browsevalues = null;
			JumpToValue("A", true, true);
		}

		private void FieldList_SelectedIndexChanged(object sender, System.EventArgs e)
		{
//			ClearResultGrid();
			browsevalues = null;
			JumpToValue("A", true, true);
		}

		private void ClearResultGrid()
		{
			TermsPanel.Visible = false;
			R.DataSource = null;
			R.DataBind();
		}
	}
}
