@namespace Oqtane.UI
@using System.ComponentModel
@using Oqtane.Shared
@inject SiteState SiteState
@implements IDisposable

@if (!string.IsNullOrEmpty(_title))
{
    @((MarkupString)_title)
}
@if (!string.IsNullOrEmpty(_content))
{
    @((MarkupString)_content)
}

@code {
    private string _title = "";
    private string _content = "";

    [Parameter]
    public string RenderMode { get; set; }

    [Parameter]
    public string Runtime { get; set; }

    protected override void OnInitialized()
    {
        ((INotifyPropertyChanged)SiteState.Properties).PropertyChanged += PropertyChanged;
    }

    private void PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        switch (e.PropertyName)
        {
            case "PageTitle":
                var title = "\n<title>" + SiteState.Properties.PageTitle + "</title>";
                if (title != _title)
                {
                    _title = title;
                    StateHasChanged();
                }
                break;
            case "HeadContent":
                var content = FormatScripts(SiteState.Properties.HeadContent) + "\n";
                if (content != _content)
                {
                    _content = content;
                    StateHasChanged();
                }
                break;
        }
    }

    private string FormatScripts(string headcontent)
    {
        if (!string.IsNullOrEmpty(headcontent))
        {
            var index = headcontent.IndexOf("<script");
            while (index >= 0)
            {
                var script = headcontent.Substring(index, headcontent.IndexOf("</script>", index) - index + 9);
                if (RenderMode == RenderModes.Interactive)
                {
                    // remove scripts when interactive rendering
                    headcontent = headcontent.Remove(index, script.Length);
                    index = headcontent.IndexOf("<script");
                }
                else
                {
                    if (!script.Contains("><") && !script.Contains("data-reload"))
                    {
                        // add data-reload attribute to inline script
                        headcontent = headcontent.Replace(script, script.Replace("<script", "<script data-reload=\"always\""));
                    }
                    index = headcontent.IndexOf("<script", index + 1);
                }
            }
        }
        return headcontent;
    }

    public void Dispose()
    {
        ((INotifyPropertyChanged)SiteState.Properties).PropertyChanged -= PropertyChanged;
    }
}