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 TermsForm : PageTemplate.OrciidPage
	{
		protected System.Web.UI.HtmlControls.HtmlGenericControl Heading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl BrowseLinkDiv;
		protected System.Web.UI.HtmlControls.HtmlContainerControl TermsPanel;

		private void Page_Load(object sender, System.EventArgs e)
		{
			Collection[] collections = null;
			int cid;
			try
			{
				cid = Int32.Parse(Request.QueryString["c"]);
				Collection coll = Collection.GetByID(cid);
				if (coll != null)
				{
					collections = new Collection[] { coll };
					Heading.InnerText = String.Format(GetLocalString(this, "HeadingWithTitle",
						"Terms for {0}"), coll.Title);
					if (coll.IsBrowsable)
					{
						HyperLink link = new HyperLink();
						link.NavigateUrl = "browse.aspx?cid=" + coll.ID;
						link.Text = GetLocalString(this, "Browse", "Browse this collection");
						BrowseLinkDiv.Controls.Add(link);
						BrowseLinkDiv.Controls.Add(new LiteralControl("<br />&nbsp;"));
					}
				}
			}
			catch
			{			
				cid = 0;
			}
			if (collections == null)
				collections = Collection.GetCollections(CollectionType.Internal);

			string reqterm = Request.QueryString["t"];
			if (reqterm != null && reqterm.Length > 0)
			{
				Search.SearchParameters parameters = new Search.SearchParameters();
				parameters.collections.AddRange(collections);
				KeywordCondition cond = new KeywordCondition();
				cond.Keyword = reqterm;
				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, "TermsResults", "Terms Results"), 
							"terms.aspx", 
							GetLocalString(this, "BackToTerms", "Back to Terms"), 
							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);
				}

			}

			FullTextIndex index = new FullTextIndex(collections);

			FullTextIndex.TermInfo[] terms = index.GetHighFrequencyTerms(1000);
			
			if (terms == null || terms.Length == 0)
				return;
			
			int[] cutoff = new int[] {
											terms[Convert.ToInt32(Math.Floor(terms.Length * 0.4))].Frequency, 
											terms[Convert.ToInt32(Math.Floor(terms.Length * 0.6))].Frequency, 
											terms[Convert.ToInt32(Math.Floor(terms.Length * 0.8))].Frequency, 
											terms[Convert.ToInt32(Math.Floor(terms.Length * 0.9))].Frequency
			};

			Array.Sort(terms, new FullTextIndex.TermInfo.AlphabeticComparer());

			foreach (FullTextIndex.TermInfo term in terms)
			{
				int style = 1;
				for (int i = 0; i < cutoff.Length; i++)
					if (term.Frequency > cutoff[i])
						style = i + 2;

				HtmlAnchor a = new HtmlAnchor();
				a.Attributes["class"] = "w" + style.ToString();
				a.InnerText = term.Term;
				a.HRef = "terms.aspx?t=" + Server.UrlEncode(term.Term) + "&c=" + cid.ToString();
				a.Title = String.Format(GetLocalString(this, "NumHits", "{0} hits"), term.Frequency);
				TermsPanel.Controls.Add(a);
				TermsPanel.Controls.Add(new LiteralControl(" "));
			}
		}

		protected override void LoadViewState(object savedState) 
		{
			if (savedState != null)
			{
				base.LoadViewState(savedState);
			}
		}

		protected override object SaveViewState()
		{
			return base.SaveViewState();
		}

		#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

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

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