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

using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using CommunityServer.Components;
using CommunityServer.Discussions.Components;

namespace CommunityServer.Discussions.Controls 
{
    
    public class BreadCrumb : Literal 
    {
        protected CSContext csContext = CSContext.Current;
        protected Queue crumbs = new Queue();
        protected HtmlAnchor anchor;

        #region Properties
		
        /// <summary>
        /// Controls whether or not the root element for the home is shown
        /// </summary>
        [
        System.ComponentModel.DefaultValue( false ),
        ]
        public virtual Boolean ShowHome 
        {
            get 
            {
                Object state = ViewState["ShowHome"];
                if ( state != null ) 
                {
                    return (Boolean)state;
                }
                return false;
            }
            set 
            {
                ViewState["ShowHome"] = value;
            }
        }

		/// <summary>
		/// Should the home link point to the Forums Home (as opposed to site home page). Default is true.
		/// </summary>
		[
		System.ComponentModel.DefaultValue( true ),
		]
		public virtual Boolean UseForumsHome 
		{
			get 
			{
				Object state = ViewState["UseForumsHome"];
				if ( state != null ) 
				{
					return (Boolean)state;
				}
				return true;
			}
			set 
			{
				ViewState["UseForumsHome"] = value;
			}
		}
		
		/// <summary>
        ///  Determines whether or not links are hook-ed up.
        /// </summary>
        [
        System.ComponentModel.DefaultValue( true ),
        ]
        public virtual Boolean EnableLinks 
        {
            get 
            {
                Object state = ViewState["EnableLinks"];
                if ( state != null ) 
                {
                    return (Boolean)state;
                }
                return true;
            }
            set 
            {
                ViewState["EnableLinks"] = value;
            }
        }

        #endregion


        protected override void CreateChildControls() 
        {

            // Do we need to add the home link?
            //
            if (ShowHome) 
            {
				if (UseForumsHome)
					crumbs.Enqueue( GetAnchor(csContext.SiteSettings.SiteName, Globals.GetSiteUrls().ForumsHome) );
				else
					crumbs.Enqueue( GetAnchor(csContext.SiteSettings.SiteName, Globals.GetSiteUrls().Home) );
			}

            // First determine the page scope
            //
            AddByRawURL(csContext.Context.Request.RawUrl);

            // Is a Forum Group ID specified?
            //
            if (csContext.GroupID > 0)
                AddForumGroup(csContext.GroupID);

            // Is a Forum ID specified?
            //
            if (csContext.SectionID > 0)
                AddForum(csContext.SectionID);

            // Is a PostID specified?
            //
            if (csContext.PostID > 0)
                AddPost(csContext.PostID);

            // We can't find anything useful on the query string
            // so we need to parse the actual URL
            //
            //AddByRawURL(csContext.Context.Request.RawUrl);
        }

        protected void AddByRawURL(string url) 
        {
            string comparisonUrl;
            int idx;
            
            // Small processing for active/unanswered/not read posts
            idx = url.IndexOf( "?", 0 );
            if (idx > 1)
                comparisonUrl = url.ToLower().Substring( 0, idx );
            else
                comparisonUrl = url.ToLower();

            // Unanswered posts
            //
            if (ForumUrls.Instance().PostsUnanswered.ToLower().IndexOf( comparisonUrl, 0 ) != -1) 
            {
                crumbs.Enqueue( GetAnchor(ResourceManager.GetString("ViewUnansweredThreads_Title"), ForumUrls.Instance().PostsUnanswered ) );
                return;
            }

            // Not read posts
            //
            if (ForumUrls.Instance().PostsNotRead.ToLower().IndexOf( comparisonUrl, 0 ) != -1) {
                crumbs.Enqueue( GetAnchor(ResourceManager.GetString("ViewNotReadThreads_Title"), ForumUrls.Instance().PostsNotRead ) );
                return;
            }

            // Active posts
            //
            if (ForumUrls.Instance().PostsActive.ToLower().IndexOf( comparisonUrl, 0 ) != -1) 
            {
                crumbs.Enqueue( GetAnchor(ResourceManager.GetString("ViewActiveThreads_Title"), ForumUrls.Instance().PostsActive ) );
                return;
            }

			// Videos
			//
			if (ForumUrls.Instance().PostsVideos.ToLower().IndexOf( comparisonUrl, 0 ) != -1)
			{
				crumbs.Enqueue( GetAnchor(ResourceManager.GetString("ViewVideos_Title"), ForumUrls.Instance().PostsVideos ) );
			}

            // Private Messages
            //
            if (Globals.GetSiteUrls().UserPrivateMessages.ToLower().IndexOf( comparisonUrl, 0 ) != -1 ||
                comparisonUrl.IndexOf( Globals.GetSiteUrls().UserPrivateMessages.ToLower(), 0 ) != -1) 
            {
                crumbs.Enqueue( GetAnchor(CommunityServer.Components.ResourceManager.GetString("PrivateMessages_Title"), Globals.GetSiteUrls().UserPrivateMessages) );
                return;
            }

            // My Forums
            //
            if (Globals.GetSiteUrls().UserMyForums.ToLower().IndexOf( comparisonUrl, 0 ) != -1) 
            {
                crumbs.Enqueue( GetAnchor(CommunityServer.Components.ResourceManager.GetString("ViewMyForumsThreads_Title"), Globals.GetSiteUrls().UserMyForums) );
                return;
            }

            // Moderation
            //
            if (url == Globals.GetSiteUrls().Moderate) 
            {
                crumbs.Enqueue( GetAnchor(ResourceManager.GetString("BreadCrumb_Moderation"), Globals.GetSiteUrls().Moderate) );
                return;
            }

            // User Profile
            //
            comparisonUrl = Globals.GetSiteUrls().UserProfile(csContext.UserID);
            if ( url == comparisonUrl) 
            {
                crumbs.Enqueue( GetAnchor( string.Format(ResourceManager.GetString("BreadCrumb_UserProfile"), Users.GetUser(csContext.UserID, false, true).Username), Globals.GetSiteUrls().UserProfile(csContext.UserID)) );
                return;
            }

            // User Profile
            //
            if ( url == Globals.GetSiteUrls().UserEditProfile)
            {
                crumbs.Enqueue( GetAnchor(ResourceManager.GetString("BreadCrumb_EditUserProfile"), Globals.GetSiteUrls().UserEditProfile) );
                return;
            }

            // Search
            //
            if ( url.IndexOf(Globals.GetSiteUrls().Search) > -1) 
            {
                crumbs.Enqueue( GetAnchor(ResourceManager.GetString("BreadCrumb_Search"), Globals.GetSiteUrls().Search) );
                return;
            }
			
			// Who is online
			//
			if ( url == Globals.GetSiteUrls().WhoIsOnline) {
				crumbs.Enqueue( GetAnchor(ResourceManager.GetString("WhoIsOnline_Title"), Globals.GetSiteUrls().WhoIsOnline) );
				return;
			}
        }

        protected void AddPost(int postID) 
        {

            // Get the Post
            //
            ForumPost p = Posts.GetPost(postID, csContext.User.UserID);

            // Get the forum
            //
            Forum f = (Forum) Forums.GetForum(p.SectionID);

			// If forum is null, it is probably a post from another application... just return to avoid null references
			if(f == null)
				return;

            // Add the forum group, only if not viewing Private Messages
            //
            if (f.SectionID > 0)
            {
                AddForumGroup(f.GroupID);

                // Recursivley add the forums
                //
                RecursivlyAddForums(f);
            } 
            else 
            {
                // We add an anchor to return to the Private Messages
                //
                crumbs.Enqueue( GetAnchor(CommunityServer.Components.ResourceManager.GetString("PrivateMessages_Title"), Globals.GetSiteUrls().UserPrivateMessages) );
            }


            // Finally add the post
            //
            crumbs.Enqueue( GetAnchor(p.Subject, Globals.GetSiteUrls().Post(p.PostID)) );

        }

        protected void RecursivlyAddForums(Forum f) 
        {
            if (f == null)
                return;

            // Recurse
            //
            if (f.ParentID > 0) 
            {
                Forum parent = Forums.GetForum(f.ParentID) as Forum;
                RecursivlyAddForums( parent );
            }

            // Next add forums
            //
            crumbs.Enqueue( GetAnchor(f.Name, ForumUrls.Instance().Forum(f.SectionID)) );

        }

        protected void AddForum(int forumID) 
        {

            // Get the forum
            //
            Forum f = Forums.GetForum(forumID, true, true) as Forum;
            User user = csContext.User;

            // Only add the forum group if the user is allowed to see it
            //
            try 
            {
                Permissions.AccessCheck(f, Permission.View, user );
                Permissions.AccessCheck(f, Permission.Read, user );

                // First add the forum group
                //
                AddForumGroup(f.GroupID);
            } 
            catch {}

            // Recursively add forums
            //
            RecursivlyAddForums(f);

        }

        protected virtual void AddForumGroup(int forumGroupID) 
        {

            // Get the forum group
            //
            Group f = ForumGroups.GetForumGroup(forumGroupID);

            crumbs.Enqueue( GetAnchor(f.Name, Globals.GetSiteUrls().ForumGroup(forumGroupID) ) );
        }

        protected Control GetAnchor(string innerText, string href) 
        {
            anchor = new HtmlAnchor();
            anchor.InnerHtml = innerText;
            anchor.Attributes["class"] = "lnk3";
            anchor.HRef = href;

            return anchor;
        }

        protected override void Render(HtmlTextWriter writer) 
        {

            while(crumbs.Count > 0) 
            {
                HtmlAnchor a = (HtmlAnchor) crumbs.Dequeue();

				// Add title for hover over, 
                // but html decoded
                //
				a.Title = Globals.HtmlDecode( a.InnerHtml );

				if ((crumbs.Count > 0) && (a.InnerHtml.Length > 30))
					a.InnerHtml = a.InnerHtml.Substring(0,30) + "...";

                a.RenderControl(writer);

                if (crumbs.Count > 0)
                    writer.Write(ResourceManager.GetString("BreadCrumb_Seperator"));

            }
            
        }

        

    }
}


