@page "/admin/aboutpageeditor"

@layout AdminControlPanelLayout


@using Microsoft.Extensions.Options
@using MudExRichTextEditor
@using MudBlazor
@using OpenArchival.Blazor
@using OpenArchival.Blazor.AdminPages.Shared
@using OpenArchival.Blazor.Config
@using OpenArchival.DataAccess
@using Microsoft.AspNetCore.Authorization

@attribute [Authorize(Roles=UserRoles.Admin)]

<MudText Typo="Typo.h6">About Page Editor</MudText>
<MudDivider></MudDivider>
<MudText Typo="Typo.body2">This is the content that will be displayed on the site's about page</MudText>
<MudExRichTextEdit @ref="@_editor"
                   ReadOnly="false"
                   Height="444"
                   Class="m-2 mt-4"
                   Placeholder="Edit html"
                   ValueHtmlBehavior="MudExRichTextEditor.Types.GetHtmlBehavior.SemanticHtml"
                   @bind-Value="_editorContent"
                   >
                   @((MarkupString)_editorContent)
                   </MudExRichTextEdit>

<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="OnSaveHomePage" Class="mt-4">Save</MudButton>

@inject ISnackbar Snackbar;
@inject IOptions<ApplicationOptions> AppOptions;
@code {
    private MudExRichTextEdit _editor = default!;

    private bool _hasLoaded = false;

    private string _editorContent = "";

    protected override void OnInitialized()
    {
        string html = "";

        if (File.Exists(AppOptions.Value.AboutPageContentLocation)) {
                using var reader = new StreamReader(AppOptions.Value.AboutPageContentLocation);
                html = reader.ReadToEnd();
            } else
            {
                Snackbar.Add("Homepage file not found, will create one on save!", Severity.Warning);
            }

            _editorContent = html;
    }

    private async Task OnSaveHomePage(Microsoft.AspNetCore.Components.Web.MouseEventArgs args)
    {
        using var writer = new StreamWriter(AppOptions.Value.AboutPageContentLocation);

        await writer.WriteLineAsync(_editorContent);

        Snackbar.Add($"Wrote homepage to {AppOptions.Value.AboutPageContentLocation}!", Severity.Success);
    }
}
