using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using TWC = Telligent.Web.UI;
using CommunityServer.Components;
using System.Text;
using System.Collections;

namespace CommunityServer.Controls
{
	public class InlineTagEditorPanel : TWC.InlineEditorPanel
	{
		CSContext csContext = CSContext.Current;
		LiteralControl literal = null;

		#region Properties
		
		int _postID = -1;
		public int PostID 
		{
			get
			{
				return _postID;
			}
			set
			{
				_postID = value;
			}
		}

		string[] _selectedTags = null;
		public string[] SelectedTags 
		{
			get
			{
				return _selectedTags;
			}
			set
			{
				_selectedTags = value;
			}
		}

		protected override string ContainerTagName
		{
			get { return "span"; }
		}

		public string LinkCssClass
		{
			get
			{
				return TWC.WebControlUtils.GetStringFromViewState(this.ViewState, "LinkCssClass", string.Empty);
			}
			set
			{
				this.ViewState["LinkCssClass"] = value;
			}
		}

		#endregion

		#region Control Overrides

		protected override void CreateChildControls()
		{
			literal = new LiteralControl();
			this.Controls.Add(literal);
		}

		protected override void OnPreRender(EventArgs e)
		{
			InlineTagEditor tagEditor = this.InlineEditor as InlineTagEditor;
			if (tagEditor != null && tagEditor.Visible && tagEditor.IsEditable(this.PostID))
				base.OnPreRender (e);
		}

		protected override void Render(HtmlTextWriter writer)
		{
			InlineTagEditor tagEditor = this.InlineEditor as InlineTagEditor;

			if (tagEditor == null)
				throw new InvalidOperationException("InlineTagEditorPanel.InlineEditor must be a valid InlineTagEditor");

			if (tagEditor.Visible)
			{
				literal.Text = tagEditor.FormatTags(this.SelectedTags);

				base.Render(writer);

				if (tagEditor.IsEditable(this.PostID))
				{
					writer.Write(" <a href=\"#\" onclick=\"");
					writer.Write("{0}.Edit({1});return false;", this.ClientID, this.PostID);
					writer.Write("\" class=\"");
					writer.Write(this.LinkCssClass);
					writer.Write("\">");
					writer.Write(ResourceManager.GetString("TagEditor_EditTags"));
					writer.Write("</a>");
				}
			}
		}

		#endregion
	}

	#region Editor Class

	public abstract class InlineTagEditor : TWC.InlineEditor
	{
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
            if(IsEditable())
			    AjaxManager.Register(this,"InlineTagEditorAJAX");
		}
		
		#region Abstract Members

		public abstract void SaveTags(int postID, string[] tags);

		public abstract string GetUrl(string tag);

		public abstract bool IsEditable (int postID);

		public abstract bool IsEditable();
		
		public abstract string[] AvailableTags { get; }

		#endregion

		#region AJAX Method

		[AjaxMethod(IncludeControlValuesWithCallBack=true)]
		public string[] SaveAndFormat(int postID, string serializedTags)
		{
			String[] newTags = serializedTags.Split(new char[] {';', ','});
			ArrayList tagsList = new ArrayList();
			for (int i = 0; i < newTags.Length; i++)
			{
				newTags[i] = PostCategories.FormatName(newTags[i].Trim());
				if (!Globals.IsNullorEmpty(newTags[i]) && !tagsList.Contains(newTags[i]))
					tagsList.Add(newTags[i]);
			}

			string[] tags = (string[]) tagsList.ToArray(typeof(string));

			this.SaveTags(postID, tags);

			return new string[] {FormatTags(tags), FormatAvailableTags()};
		}

		#endregion

		#region Properties

		protected override string SetInlineEditorPanelAndParameterFunction
		{
			get
			{
				return string.Format("new Function('id', 'p', '{0}_InlineTagEditor.SetInlineEditorPanelAndParameter(id,p);')", this.ClientID);
			}
		}

		protected override string GetContentClientFunction
		{
			get
			{
				return string.Format("new Function('return {0}_InlineTagEditor.GetContent();')", this.ClientID);
			}
		}

		protected override string SetContentClientFunction
		{
			get
			{
				return string.Format("new Function('c', '{0}_InlineTagEditor.SetContent(c);')", this.ClientID);
			}
		}

		protected override string GetStyledContextElementClientFunction
		{
			get
			{
				return "null";
			}
		}

		protected override string SetFocusClientFunction
		{
			get
			{
				return string.Format("new Function('{0}_InlineTagEditor.Focus();')", this.ClientID);
			}
		}

		protected override string ResizeClientFunction
		{
			get
			{
				return string.Format("new Function('w', 'h', '{0}_InlineTagEditor.Resize(w,h);')", this.ClientID);
			}
		}

		protected override int MinimumWidth
		{
			get
			{
				return 300;
			}
		}

		protected override int MinimumHeight
		{
			get
			{
				return 80;
			}
		}

		#endregion

		#region Public Properties

		public string CssClass
		{
			get
			{
				return TWC.WebControlUtils.GetStringFromViewState(this.ViewState, "CssClass", string.Empty);
			}
			set
			{
				this.ViewState["CssClass"] = value;
			}
		}

		public string LinkCssClass
		{
			get
			{
				return TWC.WebControlUtils.GetStringFromViewState(this.ViewState, "LinkCssClass", string.Empty);
			}
			set
			{
				this.ViewState["LinkCssClass"] = value;
			}
		}

		#endregion

		#region Rendering

		protected override void OnPreRender(EventArgs e)
		{
			if (!this.Visible || !this.IsEditable())
				return;

			base.OnPreRender(e);

			if (!this.Page.IsClientScriptBlockRegistered("CommunityServer.Controls.TagEditor"))
				this.Page.RegisterClientScriptBlock("CommunityServer.Controls.TagEditor", string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>",this.ResolveUrl("~/utility/TagEditor.js")));

			if (!this.Page.IsStartupScriptRegistered(this.ClientID + "_TagEditor"))
				this.Page.RegisterStartupScript(this.ClientID + "_TagEditor", string.Format("<script language=\"javascript\">var {0} = new TagEditor('{0}', '{1}', '{2}');</script>", this.ClientID + "_TagEditor", this.ClientID + "_AllTags", this.ClientID + "_Tags"));

			if (!this.Page.IsStartupScriptRegistered(this.ClientID + "_InlineTagEditor"))
				this.Page.RegisterStartupScript(this.ClientID + "_InlineTagEditor", string.Format("<script language=\"javascript\">var {0} = new InlineTagEditor('{0}','{1}','{2}','{3}','{4}');</script>", this.ClientID + "_InlineTagEditor", this.ClientID, this.ContainerID, this.ClientID + "_Tags", this.ClientID + "_AllTags"));
		}

		protected override void Render(HtmlTextWriter writer)
		{
			if (!this.Visible || !this.IsEditable())
				return;

			base.Render (writer);
		}


		protected override void RenderChildren(HtmlTextWriter writer)
		{
			writer.Write("<div class=\"{0}\">", this.CssClass);
			writer.Write("<textarea id=\"{0}_Tags\" style=\"width: 100%; height: 100%;\"></textarea>", this.ClientID);
			writer.Write("<div style=\"white-space: nowrap; padding-top: 4px;\">");
			writer.Write("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\"><tr><td align=\"left\">");
			writer.Write("<a href=\"#\" onclick=\"{0};return false;\" class=\"{1}\">{2}</a>", ModalHelper.BuildHandler(this.Page, SiteUrls.Instance().TagSelectorModal(Globals.UrlEncode(this.ClientID + "_TagEditor")), 400, 300, "null", false), this.LinkCssClass, ResourceManager.GetString("TagEditor_SelectTags"));
			writer.Write("</td><td align=\"right\">");
			writer.Write("<a href=\"#\" onclick=\"{0}.Save(); return false;\" class=\"{1}\">{2}</a>", this.ClientID, this.LinkCssClass, ResourceManager.GetString("Save"));
			writer.Write("<a href=\"#\" onclick=\"{0}.Close(); return false;\" class=\"{1}\">{2}</a>", this.ClientID, this.LinkCssClass, ResourceManager.GetString("Cancel"));
			writer.Write("</td></tr></table></div></div>");
			writer.Write("<input type=\"hidden\" id=\"{0}_AllTags\" value=\"{1}\" />", this.ClientID, this.FormatAvailableTags());
		}

		public virtual string FormatAvailableTags()
		{
			StringBuilder list = new StringBuilder();
			if (this.AvailableTags != null)
			{
				foreach (string tag in this.AvailableTags)
				{
					if (list.Length > 0)
						list.Append("&");

					list.Append(Globals.UrlEncode(System.Web.HttpUtility.HtmlDecode(tag)));
					list.Append("&");
					list.Append(Globals.UrlEncode(tag));
				}
			}

			return list.ToString();
		}

		public virtual string FormatTags(string[] tagList)
		{
			StringBuilder tagString = new StringBuilder();

			if (tagList != null && tagList.Length > 0)
			{
				tagString.Append(ResourceManager.GetString("TagListTitle"));

				for (int i = 0; i < tagList.Length; i++)
				{
					if (i > 0)
						tagString.Append(ResourceManager.GetString("TagListDelimiter"));

					tagString.Append("<a href=\"");
					tagString.Append(this.GetUrl(tagList[i]));
					tagString.Append("\" rel=\"tag\">");
					tagString.Append(tagList[i]);
					tagString.Append("</a>");
				}
			}

			return tagString.ToString();
		}

		#endregion
	}

	#endregion
}
