@namespace Oqtane.UI
@using Microsoft.AspNetCore.Http
@inject IInstallationService InstallationService
@inject IJSRuntime JSRuntime
@inject SiteState SiteState
@* the following StreamRendering attribute is required - if it is removed the framework will not render the content in static rendering *@
@attribute [StreamRendering] 

@if (_initialized)
{
    @if (!_installation.Success)
    {
        <Installer />
    }
    else
    {
        @if (string.IsNullOrEmpty(_installation.Message))
        {
            <div style="@_display">
                <CascadingValue Value="@_pageState">
                    <SiteRouter RenderMode="@RenderMode" Runtime="@Runtime" OnStateChange="@ChangeState" />
                </CascadingValue>
            </div>
        }
        else
        {
            <div class="app-alert">
                @_installation.Message
            </div>
        }
    }
}

@code {
    [Parameter]
    public PageState PageState { get; set; } = null;

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

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

    [Parameter]
    public string AntiForgeryToken { get; set; } = "";

    [Parameter]
    public string AuthorizationToken { get; set; } = "";

    [CascadingParameter]
    HttpContext HttpContext { get; set; }

    private bool _initialized = false;
    private string _display = "";
    private Installation _installation = new Installation { Success = false, Message = "" };

    private PageState _pageState { get; set; }

    protected override async Task OnParametersSetAsync()
    {
        if (PageState != null)
        {
            _pageState = PageState;            
        }

        if (RenderMode == RenderModes.Interactive)
        {
            _display = "display: none;";
        }

        SiteState.AntiForgeryToken = AntiForgeryToken;
        SiteState.AuthorizationToken = AuthorizationToken;
        SiteState.RemoteIPAddress = (_pageState != null) ? _pageState.RemoteIPAddress : "";
        SiteState.IsPrerendering = (HttpContext != null) ? true : false;

        _installation = await InstallationService.IsInstalled();
        if (_installation.Alias != null)
        {
            SiteState.Alias = _installation.Alias;
        }
        _initialized = true;
    }

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            // prevents flash on initial interactive page load
            _display = "";
            StateHasChanged();
        }
    }

    private void ChangeState(PageState pageState)
    {
        _pageState = pageState;
        StateHasChanged();
    }
}
