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

using System;
using System.Collections;
using System.Text.RegularExpressions;
using CommunityServer.Components;
using CommunityServer.Files.Components;
using CA = ComponentArt.Web.UI;
using Group = CommunityServer.Components.Group;

namespace CommunityServer.Files.Controls
{
	public class FolderTree: FileGalleryTemplatedWebControl
	{
	    CSContext csContext = CSContext.Current;

		protected string AjaxQueryStringKey
		{
			get
			{
				return "___" + this.ClientID;
			}
		}

		protected string AjaxQueryStringValue = "{0}:{1}";
		protected string AjaxQueryStringValuePattern = "(\\d+):([\\w\\.-]*)";

		public bool PreLoadFolders
		{
			get
			{
				object state = ViewState["PreLoadFolders"];
				if (state == null)
					return false;
				else
					return (bool) state;
			}
			set
			{
				ViewState["PreLoadFolders"] = value;
			}
		}

		public bool PreLoadCategories
		{
			get
			{
				object state = ViewState["PreLoadCategories"];
				if (state == null)
					return false;
				else
					return (bool) state;
			}
			set
			{
				ViewState["PreLoadCategories"] = value;
			}
		}

		public bool ShowCategories
		{
			get
			{
				object state = ViewState["ShowCategories"];
				if (state == null)
					return false;
				else
					return (bool) state;
			}
			set
			{
				ViewState["ShowCategories"] = value;
			}
		}

		#region Child Controls

		private CA.TreeView Tree;

		#endregion

		#region Skin

		protected override void AttachChildControls()
		{
			Tree = (CA.TreeView)FindControl("Tree");
		}

		#endregion

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			if (this.Page.Request.QueryString[AjaxQueryStringKey] != null)
				HandleXmlRequest(this.Page.Request.QueryString[AjaxQueryStringKey]);

			this.DataBind();
		}

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



		private void BuildGroupTree()
		{
			if (Tree == null)
				return;

			Folder f = null;
			if (!Globals.IsNullorEmpty(csContext.ApplicationKey))
				f = Folders.GetFolder(csContext.ApplicationKey);

			Tree.Nodes.Clear();
		    ArrayList folderGroups = Folders.GetFolderGroups(csContext.UserID, true, false, false);
			CA.TreeViewNode node;
			foreach (Group group in folderGroups)
			{
				node = new CA.TreeViewNode();
				node.Text = group.Name;
				if (node.Text.Length > 30)
					node.Text = node.Text.Substring(0, 27) + "...";

				node.NavigateUrl = FileGalleryUrls.Instance().ViewFolderGroup(group.GroupID);

				Tree.Nodes.Add(node);

				if ((f != null && group.GroupID == f.GroupID) || group.GroupID == csContext.GroupID)
				{
					node.Expanded = true;
					if (Globals.IsNullorEmpty(csContext.ApplicationKey))
					{
						node.CssClass = Tree.SelectedNodeCssClass;
						node.HoverCssClass = Tree.SelectedNodeCssClass;
					}

					BuildFolderTree(group.GroupID, node.Nodes);
				}
				else if (this.PreLoadFolders)
				{
					BuildFolderTree(group.GroupID, node.Nodes);
				}
				else
				{
					node.ContentCallbackUrl = CreateCallbackUrl(group.GroupID, "");
				}
			}
		}

		private void BuildFolderTree(int groupID, CA.TreeViewNodeCollection nodes)
		{
			ArrayList folders = Folders.GetFoldersByGroupID(groupID, false, true, false);
			CA.TreeViewNode node;
			foreach (Folder folder in folders)
			{
				if (folder.IsActive)
				{
					node = new CA.TreeViewNode();
					if (folder.Name.Length > 30)
						node.Text = folder.Name.Substring(0, 27) + "...";
					else
						node.Text = folder.Name;

					node.Text += " (" + folder.TotalThreads.ToString() + ")";
					node.NavigateUrl = FileGalleryUrls.Instance().ViewFolder(folder.ApplicationKey);

					nodes.Add(node);

					if (this.ShowCategories)
					{
						if (csContext.ApplicationKey == folder.ApplicationKey)
						{
							node.Expanded = true;
							if (csContext.CategoryID == -1)
							{
								node.CssClass = Tree.SelectedNodeCssClass;
								node.HoverCssClass = Tree.SelectedNodeCssClass;
							}

							BuildCategoryTree(folder.ApplicationKey, node.Nodes);
						}
						else if (this.PreLoadCategories)
						{
							BuildCategoryTree(folder.ApplicationKey, node.Nodes);
						}
						else
						{
							node.ContentCallbackUrl = CreateCallbackUrl(groupID, folder.ApplicationKey);
						}
					}
					else if (csContext.ApplicationKey == folder.ApplicationKey)
					{
						node.CssClass = Tree.SelectedNodeCssClass;
						node.HoverCssClass = Tree.SelectedNodeCssClass;
					}

				}
			}
		}

		private void BuildCategoryTree(string appKey, CA.TreeViewNodeCollection nodes)
		{
			Folder folder = Folders.GetFolder(appKey);
			ArrayList categories = PostCategories.GetCategories(folder.SectionID, true, 0);
			CA.TreeViewNode node;
			foreach (PostCategory category in categories)
			{
				node = new CA.TreeViewNode();
				if (category.Name.Length > 30)
					node.Text = category.Name.Substring(0, 27) + "...";
				else
					node.Text = category.Name;

				node.Text += " (" + category.TotalThreads.ToString() + ")";
				node.NavigateUrl = FileGalleryUrls.Instance().ViewCategory(appKey, category.CategoryID);

				nodes.Add(node);

				if (csContext.CategoryID == category.CategoryID)
				{
					node.CssClass = Tree.SelectedNodeCssClass;
					node.HoverCssClass = Tree.SelectedNodeCssClass;
				}
			}

		}

		protected virtual string CreateCallbackUrl(int groupID, string appKey)
		{
			string value = String.Format(AjaxQueryStringValue, groupID, appKey);
			string url = csContext.CurrentUri.AbsoluteUri;

			if (url.IndexOf("?") == -1)
			{
				url += "?" + AjaxQueryStringKey + "=" + value;
			}
			else
			{
				if (url.IndexOf(AjaxQueryStringKey + "=") == -1)
					url += "&" + AjaxQueryStringKey + "=" + value;
				else
				{
					url = Regex.Replace(url, AjaxQueryStringKey + "=([^&]+)", AjaxQueryStringKey + "=" + value);
				}
			}

			return url;
		}

		protected void HandleXmlRequest(string value)
		{
			Match m = Regex.Match(value, AjaxQueryStringValuePattern);
			if (m != null)
			{
				csContext.GroupID = int.Parse(m.Groups[1].Value);
				csContext.ApplicationKey = m.Groups[2].Value;

				CA.TreeView tree = new CA.TreeView();

				if (Globals.IsNullorEmpty(csContext.ApplicationKey))
					BuildFolderTree(csContext.GroupID, tree.Nodes);
				else
					BuildCategoryTree(csContext.ApplicationKey, tree.Nodes);

				Page.Response.Clear();
				Page.Response.ContentType = "text/xml";
				Page.Response.Write(tree.GetXml());
				Page.Response.End();
			}
		}
	}
}
