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

using System;
using System.ComponentModel;
using System.Text;
using System.Web.UI.HtmlControls;
using CommunityServer.Components;


namespace CommunityServer.Controls
{
    public class ThreadSubscribeLinkButton : HtmlAnchor, ITrackedThread
	{

		#region Public Properties

        private bool _isTracked;
        private int _postid, _threadid;

        public bool IsTracked
        {
            get{return _isTracked;}
            set{_isTracked = value;}
        }

        public int PostID
        {
            get{return _postid;}
            set{_postid = value;}
        }

        public int ThreadID
        {
            get{return _threadid;}
            set{_threadid = value;}
        }

		[
		Bindable(true),
		Category( "Appearance" ),
		Description( "Gets or sets whether images will be used with the button." ),
		DefaultValue( false ),
		]
		public virtual bool UseImages
		{
			get
			{
				Object state = ViewState["UseImages"];
				if(state != null)
					return (bool)state;
				return false;
			}
			set { ViewState["UseImages"] = value; }
		}

		[
		Bindable(true),
		Category( "Appearance" ),
		Description( "Gets or sets the name of the resource to display when tracking." ),
		DefaultValue( "" ),
		]
		public virtual string TrackingResourceName 
		{
			get 
			{
				Object state = ViewState["TrackingResourceName"];
				if ( state != null ) 
					return (string)state;
				return "";
			}
			set { ViewState["TrackingResourceName"] = value; }
		}

		[
		Bindable(true),
		Category( "Appearance" ),
		Description( "Gets or sets the name of the resource to display when not tracking." ),
		DefaultValue( "" ),
		]
		public virtual string NotTrackingResourceName 
		{
			get 
			{
				Object state = ViewState["NotTrackingResourceName"];
				if ( state != null ) 
					return (string)state;
				return "";
			}
			set { ViewState["NotTrackingResourceName"] = value; }
		}

		[
		Bindable(true),
		Category( "Appearance" ),
		Description( "Gets or sets the name of the resource to display when the button is working." ),
		DefaultValue( "" ),
		]
		public virtual string WorkingResourceName 
		{
			get 
			{
				Object state = ViewState["WorkingResourceName"];
				if ( state != null ) 
					return (string)state;
				return "";
			}
			set { ViewState["WorkingResourceName"] = value; }
		}

		[
		System.ComponentModel.DefaultValue("CommonImageTextButton")
		]
		public virtual String CssClass
		{
			get
			{
				Object state = ViewState["CssClass"];
				if ( state != null ) 
				{
					return (String)state;
				}
				return "CommonImageTextButton";
			}
			set
			{
				ViewState["CssClass"] = value;
			}
		}

		#endregion

		protected override void OnLoad(EventArgs e)
		{
            if(!CSContext.Current.User.IsAnonymous)
			    AjaxManager.Register(this,this.GetType().Name,true,AjaxDebug.None);

			base.OnLoad (e);
		}


		#region Control Wiring

		protected override void CreateChildControls()
		{
			if(CSContext.Current.User.IsAnonymous)
				return;

			if(UseImages)
			{
				this.Attributes.Add("onMouseOver", "javascript:subscriptionButtonOver();");
				this.Attributes.Add("onMouseOut", "javascript:subscriptionButtonOut();");
				this.Attributes.Add("onMouseDown", "this.style.backgroundImage = 'url(" + Globals.GetSkinPath() + "/images/common/tracktopic-wait.gif)';");
				this.Attributes.Add("class", this.CssClass);

				if(this.IsTracked)
				{
					this.Attributes.Add("style", "background-image: url(" + Globals.GetSkinPath() + "/images/common/tracktopic-on.gif);");
					this.InnerText = ResourceManager.GetString(TrackingResourceName);
				}
				else
				{
					this.Attributes.Add("style", "background-image: url(" + Globals.GetSkinPath() + "/images/common/tracktopic.gif);");
					this.InnerText = ResourceManager.GetString(NotTrackingResourceName);
				}
			}
			else
			{
				if(this.IsTracked)
					this.InnerText = ResourceManager.GetString(TrackingResourceName);
				else
					this.InnerText = ResourceManager.GetString(NotTrackingResourceName);
			}

			this.HRef = "javascript:toggleSubscription();";
		}

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

			if(CSContext.Current.User.IsAnonymous)
				return;
			
			if(UseImages)
				BuildCallbackScriptWithImages();
			else
				BuildCallbackScript();
		}

		private void BuildCallbackScript()
		{
			StringBuilder sb = new StringBuilder();
			string uniqueID = this.ClientID;

			sb.Append("<script language='JavaScript' type=\"text/javascript\">");
			sb.AppendFormat("var {0}_trackWorking = false;", uniqueID);
			sb.AppendFormat("var {0}_trackStatus = {1};", uniqueID, this.IsTracked.ToString().ToLower());

			sb.Append("function updateSubscriptionText() {");
			sb.Append(  "if(" + uniqueID + "_trackStatus == true) {");
			if(TrackingResourceName != string.Empty)
				sb.Append(    "document.getElementById('" + uniqueID + "').innerHTML = '" + ResourceManager.GetString(TrackingResourceName).Replace("'", "\'") + "';");
			sb.Append(  "} else {");
			if(NotTrackingResourceName != string.Empty)
				sb.Append(    "document.getElementById('" + uniqueID + "').innerHTML = '" + ResourceManager.GetString(NotTrackingResourceName).Replace("'", "\'") + "';");
			sb.Append(  "}");
			sb.Append("}");

			sb.Append("function toggleSubscription() {");
			sb.Append(  uniqueID + "_trackWorking = true;");
			if(WorkingResourceName != string.Empty)
				sb.Append(  "document.getElementById('" + uniqueID + "').innerHTML = '" + ResourceManager.GetString(WorkingResourceName).Replace("'", "\'") + "';");
			sb.Append(  this.GetType().Name + ".ToggleEmailReplies('" + this.ClientID + "'," + this.ThreadID +  ", toggleSubscriptionCallback);");
			sb.Append("}");

			sb.Append("function toggleSubscriptionCallback(response) {");
			sb.Append(  uniqueID + "_trackWorking = false;");

			sb.Append(  "if((response.error == null) && (response.value == true)) {");
			sb.Append(    "if(" + uniqueID + "_trackStatus == true) {");
			sb.Append(      uniqueID + "_trackStatus = false;");
			sb.Append(    "} else {");
			sb.Append(      uniqueID + "_trackStatus = true;");
			sb.Append(    "}");
			sb.Append(    "updateSubscriptionText();");
			sb.Append(  "} else {");
			sb.Append(    "updateSubscriptionText();");
			sb.Append(    "alert('" + ResourceManager.GetString("CallbackErrorResponse").Replace("'", "\'") + "');");
			sb.Append(  "}");
			sb.Append("}");
			sb.Append("</script>");

			Page.RegisterClientScriptBlock("ThreadSubscribeCallback", sb.ToString());
		}

		private void BuildCallbackScriptWithImages()
		{
			StringBuilder sb = new StringBuilder();
			string uniqueID = this.ClientID;
			string imageUniqueID = this.ClientID;

			sb.Append("<script language='JavaScript' type=\"text/javascript\">");
			sb.AppendFormat("var {0}_trackWorking = false;", uniqueID);
			sb.AppendFormat("var {0}_trackStatus = {1};", uniqueID, this.IsTracked.ToString().ToLower());

			sb.Append("function subscriptionButtonOut() {");
			sb.Append(  "if(" + uniqueID + "_trackWorking == false) {");
			sb.Append(    "if(" + uniqueID + "_trackStatus == true) {");
			sb.Append(		"document.getElementById('" + imageUniqueID + "').style.backgroundImage = 'url(" + Globals.GetSkinPath() + "/images/common/tracktopic-on.gif)';");
			if(TrackingResourceName != string.Empty)
			{
				sb.Append(      "document.getElementById('" + imageUniqueID + "').innerHTML = '" + ResourceManager.GetString(TrackingResourceName).Replace("'", "\'") + "';");
			}
			sb.Append(    "} else {");
			sb.Append(		"document.getElementById('" + imageUniqueID + "').style.backgroundImage = 'url(" + Globals.GetSkinPath() + "/images/common/tracktopic.gif)';");
			if(NotTrackingResourceName != string.Empty)
			{
				sb.Append(      "document.getElementById('" + imageUniqueID + "').innerHTML = '" + ResourceManager.GetString(NotTrackingResourceName).Replace("'", "\'") + "';");
			}
			sb.Append(    "}");
			sb.Append(  "}");
			sb.Append("}");

			sb.Append("function subscriptionButtonOver() {");
			sb.Append(  "if(" + uniqueID + "_trackWorking == false) {");
			if(WorkingResourceName != string.Empty)
			{
				sb.Append(    "document.getElementById('" + imageUniqueID + "').innerHTML = '" + ResourceManager.GetString(WorkingResourceName).Replace("'", "\'") + "';");
			}
			sb.Append(  "}");
			sb.Append("}");

			sb.Append("function toggleSubscription() {");
			sb.Append(  uniqueID + "_trackWorking = true;");
			sb.Append(  this.GetType().Name + ".ToggleEmailReplies('" + this.ClientID + "'," + this.ThreadID + ", toggleSubscriptionCallback);");
			sb.Append("}");

			sb.Append("function toggleSubscriptionCallback(response) {");
			sb.Append(  uniqueID + "_trackWorking = false;");
			sb.Append(  "if((response.error == null) && (response.value == true)) {");
			sb.Append(    "if(" + uniqueID + "_trackStatus == true) {");
			sb.Append(      uniqueID + "_trackStatus = false;");
			sb.Append(      "subscriptionButtonOut();");
			sb.Append(    "} else {");
			sb.Append(      uniqueID + "_trackStatus = true;");
			sb.Append(      "subscriptionButtonOut();");
			sb.Append(    "}");
			sb.Append(  "} else {");
			sb.Append(    "subscriptionButtonOut();");
			sb.Append(    "alert(response.error);");
			sb.Append(  "}");
			sb.Append("}");
			sb.Append("</script>");

			Page.RegisterClientScriptBlock("ThreadSubscribeCallback", sb.ToString());
		}

		#endregion

		#region Event Handlers/Callbacks

		/// <summary>
		/// This method is the callback when a user clicks on the button to toggle their tracking status.  It calls the abstract Toggle()
		/// method to switch the user's tracking status and then returns whether or not it was successful.
		/// </summary>
		/// <returns>This returns true/false to indicate whether the switch was successful or not.</returns>
		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public bool ToggleEmailReplies(int threadID)
		{
			try
			{
                CSContext context = CSContext.Current;
                if(!context.User.IsAnonymous)
                {
                    ThreadTracking.ReverseThreadTrackingOptions(threadID, context.User.UserID);
                    return true;
                }
                return false;
			}
			catch(Exception e)
			{
				new CSException(CSExceptionType.UnknownError, "Error in ThreadSubscribeLinkButton callback", e).Log();
				throw e;
			}
		}

		#endregion

	}
}
