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

namespace Localization.Controls
{
    public class CurrencyTextBox : TextBox, IScriptControl
    {
        private ScriptManager _scriptManager;
        
        protected ScriptManager PageScriptManager
        {
            get
            {
                if (_scriptManager == null)
                {
                    _scriptManager = ScriptManager.GetCurrent(this.Page);
                }

                return _scriptManager;
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (!DesignMode)
            {
                if (PageScriptManager == null)
                {
                    throw new InvalidOperationException("ScriptManager not present on page.");
                }
                PageScriptManager.RegisterScriptControl<CurrencyTextBox>(this);
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            if (!DesignMode)
            {
                if (PageScriptManager == null)
                {
                    throw new InvalidOperationException("ScriptManager not present on page.");
                }
                PageScriptManager.RegisterScriptDescriptors(this);
            }
        }

        #region IScriptControl Members

        public IEnumerable<ScriptDescriptor> GetScriptDescriptors()
        {
            ScriptControlDescriptor sbd = new ScriptControlDescriptor("Localization.Controls.CurrencyTextBox", this.ClientID);
            if (!string.IsNullOrEmpty(this.Text))
            {
                sbd.AddProperty("unFormattedValue", this.Text);
            }
            yield return sbd;
        }

        public IEnumerable<ScriptReference> GetScriptReferences()
        {
            yield return new ScriptReference("Localization.Controls.ClientScript.CurrencyTextBox.js", typeof(CurrencyTextBox).Assembly.FullName);
        }

        #endregion
    }
}
