using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.UI;

namespace AjaxUploader.Demos
{
    public partial class SiteMaster : MasterPage
    {
        private static readonly Regex TitleWhitespace =
            new Regex(@"<title>\s*([\s\S]*?)\s*</title>", RegexOptions.Compiled);

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Normalises the rendered &lt;title&gt;. With <c>&lt;head runat="server"&gt;</c>,
        /// ASP.NET's HtmlHead swaps in its own HtmlTitle at render time and pads the text
        /// with "\r\n\t" - so trimming Page.Title earlier in the lifecycle changes nothing.
        /// Browsers show the padding as a leading space in the tab and search engines
        /// index it verbatim. Post-processing the head output is the only reliable seam,
        /// and doing it in the master fixes all 131 demo pages at once.
        /// </summary>
        protected override void Render(HtmlTextWriter writer)
        {
            using (var buffer = new StringWriter())
            using (var inner = new HtmlTextWriter(buffer))
            {
                base.Render(inner);
                var html = buffer.ToString();
                var headEnd = html.IndexOf("</head>", StringComparison.OrdinalIgnoreCase);
                if (headEnd > 0)
                {
                    var head = TitleWhitespace.Replace(html.Substring(0, headEnd),
                        m => "<title>" + Regex.Replace(m.Groups[1].Value, @"\s+", " ") + "</title>", 1);
                    html = head + html.Substring(headEnd);
                }
                writer.Write(html);
            }
        }
    }
}
