//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Controls;

namespace CommunityServer.Controls 
{

	// *********************************************************************
	//  SearchView
	//
	/// <summary>
	/// This server control is used to display search options and search results
	/// </summary>
	/// 
	// ********************************************************************/
	public class SearchResults : TemplatedWebControl 
	{

		#region Constructor and Member Variables
		CSContext csContext = CSContext.Current;
		string searchQuery;
		Label searchFor;
		TextBox searchTextTop;
		TextBox searchTextBottom;
		Button searchButtonTop;
		Button searchButtonBottom;
		Repeater searchRepeater;
		CurrentPage resultTotal;
		Literal searchDuration;
		Pager pager;
		HtmlGenericControl validatorTop;
		HtmlGenericControl validatorBottom;
		StatusMessage formStatus;
		Panel searchResultsDisplay;
		ApplicationType applicationType;
		Panel searchRssOption;
		RssButton Rss;
		string currentItemSiteUrl = string.Empty;

		// *********************************************************************
		//  SearchView
		//
		/// <summary>
		/// The constructor simply checks for a ForumID value passed in via the
		/// HTTP POST or GET.
		/// properties.
		/// </summary>
		/// 
		// ********************************************************************/
		public SearchResults() 
		{
			applicationType = (ApplicationType)csContext.GetIntFromQueryString("a", 9999);
		}

		/// <summary>
		/// If not a page back, calls DataBind()
		/// </summary>
		/// <param name="e"></param>
		protected override void OnLoad(EventArgs e) 
		{
			if ( !Page.IsPostBack ) 
			{
				this.DataBind();
			}
			base.OnLoad (e);

            UsersOnline.SetLocation("Viewing Search Results");
		}

		#endregion

		#region Render
		// *********************************************************************
		//  AttachChildControls
		//
		/// <summary>
		/// Initializes the user control loaded in CreateChildControls. Initialization
		/// consists of finding well known control names and wiring up any necessary events.
		/// </summary>
		/// 
		// ********************************************************************/ 
		protected override void AttachChildControls() 
		{

			if (!Page.IsPostBack) 
			{
				searchQuery = csContext.Context.Request.QueryString["q"];
				//searchUsers = CommunityServer.Search.UsersToDecode (csContext.Context.Request.QueryString["u"] );
			}

			// Find all the controls
			//
			searchFor				= (Label) FindControl("ForumDescription");
			searchTextTop           = (TextBox) FindControl("SearchTextTop");
			searchTextBottom        = (TextBox) FindControl("SearchTextBottom");
			searchButtonTop         = FindControl("SearchButtonTop") as Button;
			searchButtonBottom      = FindControl("SearchButtonBottom") as Button;
			searchButtonTop.Text    = ResourceManager.GetString("Search");
			searchButtonBottom.Text = ResourceManager.GetString("Search");
			searchRepeater          = FindControl("SearchRepeater") as Repeater;
			pager                   = (Pager) FindControl("Pager");
			resultTotal             = (CurrentPage) FindControl("TotalResults");
			resultTotal.TextFormat  = ResourceManager.GetString("SearchResults_TotalResults");
			searchDuration          = (Literal) FindControl("SearchDuration");
			searchDuration.Text     = ResourceManager.GetString("SearchResults_SearchDuration");
			formStatus				= FindControl("formStatus") as StatusMessage;
			validatorTop			= (HtmlGenericControl) FindControl("SearchBoxValidatorTop");
			validatorBottom			= (HtmlGenericControl) FindControl("SearchBoxValidatorBottom");
			searchResultsDisplay	= FindControl("SearchResultsDisplay") as Panel;
			Rss = FindControl("RSS") as RssButton;
			searchRssOption = FindControl("SearchRssOption") as Panel;

			if (FindControl("ForumName") != null)
				((Label) FindControl("ForumName")).Text = ResourceManager.GetString("SearchViewSimple_Title");
			

			// Set up the OnItemCommand for the DataList
			//
			searchRepeater.ItemCommand += new RepeaterCommandEventHandler(Display_Item);
			searchRepeater.ItemDataBound += new RepeaterItemEventHandler( SearchRepeater_ItemDataBound );
			searchButtonTop.Click += new EventHandler(Search_Click);
			searchButtonBottom.Click += new EventHandler(Search_Click);


			// Set the pager size
			//
			pager.PageSize = csContext.SiteSettings.SearchPostsPerPage;

			// Set the values in our textboxes
			//
			searchTextTop.Text = searchQuery;
			searchTextBottom.Text = searchQuery;
		}
		#endregion

		public void Search_Click (Object sender, EventArgs e) 
		{
			bool isSearchTextInTopTextBox = true;

			// Which search text is being used?
			//
			if ( ((Button) sender).ID != "SearchButtonTop" )
				isSearchTextInTopTextBox = false;

			// Set the text to the correct values
			//
			if (isSearchTextInTopTextBox)
			{
				if(searchTextTop.Text.Trim() == string.Empty)
				{
					validatorTop.Visible = true;
					return;
				}
				else
				{
					validatorTop.Visible = false;
					searchTextBottom.Text = searchTextTop.Text;
				}
			}
			else
			{
				if(searchTextBottom.Text.Trim() == string.Empty)
				{
					validatorBottom.Visible = true;
					return;
				}
				else
				{
					validatorBottom.Visible = false;
					searchTextTop.Text = searchTextBottom.Text;
				}
			}

			SearchQuery query = SearchProvider.Instance().GetSearchQueryFromQueryString(this.Page.Request.QueryString);
			query.QueryText = searchTextTop.Text;
			
			HttpContext.Current.Response.Redirect(Globals.GetSiteUrls().SearchForText(SearchProvider.Instance().SearchQueryString(query)));
		}

		public override void DataBind() 
		{
			base.DataBind();

			SearchResultSet searchResult = null;
			int resultCountUpper, resultCountLower;

			// Set the "search for" text
			//
			searchFor.Text = string.Format(ResourceManager.GetString("SearchViewSimple_SearchFor"), Globals.HtmlEncode(searchTextTop.Text));

			// Get the search results
			// 

			SearchQuery query = SearchProvider.Instance().GetSearchQueryFromQueryString(this.Page.Request.QueryString);
			query.PageIndex = pager.PageIndex;
			query.PageSize = pager.PageSize;
                    
			searchResult = CSSearch.Search(query);
			if (!searchResult.HasResults)
			{
				searchResultsDisplay.Visible = false;
				formStatus.Visible = true;
				formStatus.Success = false;
				formStatus.ResourceName = "SearchView_NoResults";

				return;
			}

			if(csContext.SiteSettings.EnableRssSearch && searchResult.TotalRecords > 0 && searchRssOption != null && Rss != null)
			{
				searchRssOption.Visible = true;
				Rss.NavigateUrl= Globals.GetSiteUrls().SearchRss(SearchProvider.Instance().SearchQueryString(query));
			}

			// Set the TotalRecords in the pager
			//    
			pager.TotalRecords = searchResult.TotalRecords;

			// Databind
			//
			searchRepeater.DataSource = searchResult.Posts;
			searchRepeater.DataBind();

			resultCountLower = 1 + (pager.PageIndex * pager.PageSize);

			// Set the upper bounds of the search results text
			//
			if (pager.TotalRecords > pager.PageSize) 
				resultCountUpper = pager.PageSize + (pager.PageSize * pager.PageIndex);
			else
				resultCountUpper = searchResult.TotalRecords;

			// Setup the result total
			resultTotal.PageIndex = pager.PageIndex;
			resultTotal.TotalPages = pager.CalculateTotalPages();
			resultTotal.TotalRecords = pager.TotalRecords;

			if (searchResult.SearchDuration < 1)
				searchDuration.Text = string.Format(searchDuration.Text, "< 1");
			else
				searchDuration.Text = string.Format(searchDuration.Text, searchResult.SearchDuration);

		}

		public void Display_Item (Object sender, RepeaterCommandEventArgs e) 
		{

			HttpContext.Current.Response.Write( e.CommandArgument );
			DataBind();

		}
		
		/// <summary>
		/// Added to handle Username displaying
		/// </summary>
		protected void SearchRepeater_ItemDataBound (Object Sender, RepeaterItemEventArgs e) 
		{
			IndexPost post = e.Item.DataItem as IndexPost;
			if (post == null)
				return;
            
			switch (e.Item.ItemType) 
			{
				case  ListItemType.Item:
				case  ListItemType.AlternatingItem:
				
                    HyperLink SectionUrl = e.Item.FindControl("SectionUrl") as HyperLink;
                    if(SectionUrl != null && Globals.IsNullorEmpty(SectionUrl.NavigateUrl))
                    {
                        CSApplicationData data = ApplicationSet.Data(post.ApplicationType);
                        if(data != null)
                        {
							string sectionUrl = data.SectionUrl(post);
							if(post.SettingsID != csContext.SettingsID)
							{
								SiteSettings siteSettings = SiteSettingsManager.GetSiteSettings(post.SettingsID);
								if(sectionUrl.StartsWith(Globals.ApplicationPath))
									sectionUrl = sectionUrl.Remove(0, Globals.ApplicationPath.Length); 
								sectionUrl = Globals.FullPath(siteSettings.SiteUrl, sectionUrl); 
							}
                            SectionUrl.NavigateUrl = sectionUrl;
                        }
                        else
                        {
                            SectionUrl.Visible = false;
                        }
                    }

					HyperLink ApplicationUrl = e.Item.FindControl("ApplicationUrl") as HyperLink;
					if(ApplicationUrl != null && Globals.IsNullorEmpty(ApplicationUrl.NavigateUrl))
					{
						string applicaitonUrl = post.ApplicationUrl;
						if(post.SettingsID != csContext.SettingsID)
						{
							SiteSettings siteSettings = SiteSettingsManager.GetSiteSettings(post.SettingsID);
							if(applicaitonUrl.StartsWith(Globals.ApplicationPath))
								applicaitonUrl = applicaitonUrl.Remove(0, Globals.ApplicationPath.Length); 
							applicaitonUrl = Globals.FullPath(siteSettings.SiteUrl, applicaitonUrl); 
						}
						ApplicationUrl.NavigateUrl = applicaitonUrl;
						ApplicationUrl.Text = string.Format("({0})",post.ApplicationType) ;
					}

					HyperLink ProfileUrl = e.Item.FindControl("ProfileUrl") as HyperLink;
					if(ProfileUrl != null)
					{
                        if (Globals.IsNullorEmpty(ProfileUrl.NavigateUrl))
                        {
                            string profileUrl = SiteUrls.Instance().UserProfile(post.UserName);
                            if (post.SettingsID != csContext.SettingsID)
                            {
                                SiteSettings siteSettings = SiteSettingsManager.GetSiteSettings(post.SettingsID);
                                if (profileUrl.StartsWith(Globals.ApplicationPath))
                                    profileUrl = profileUrl.Remove(0, Globals.ApplicationPath.Length);
                                profileUrl = Globals.FullPath(siteSettings.SiteUrl, profileUrl);
                            }
                            ProfileUrl.NavigateUrl = profileUrl;
                        }

                        if (Globals.IsNullorEmpty(ProfileUrl.Text))
                        {
                            User u = Users.FindUserByUsername(post.UserName);
                            if (u != null && !u.IsAnonymous)
                                ProfileUrl.Text = u.DisplayName;
                            else
                                ProfileUrl.Text = post.UserName;
                        }
					}

					break;
			}
		}
	}
}
