@page "/admin/system/news"
@using Moonlight.App.Repositories
@using Moonlight.App.Database.Entities
@using Markdig
@using Moonlight.App.Helpers
@using Moonlight.App.Services
@using Moonlight.App.Services.Interop
@using Moonlight.Shared.Components.Navigations
@using Moonlight.Shared.Components.FileManagerPartials

@inject NewsEntryRepository NewsEntryRepository
@inject SmartTranslateService SmartTranslateService
@inject AlertService AlertService

<OnlyAdmin>
    <AdminSystemNavigation Index="7" />
    
    <div class="card card-body mb-6">
        <div class="text-end">
            <a href="/admin/system/news/new" class="btn btn-success">
                <TL>New entry</TL>
            </a>
        </div>
    </div>

    <LazyLoader @ref="LazyLoader" Load="Load">
        @foreach (var entry in Entries)
        {
            <div class="card mb-6">
                <div class="card-header">
                    <h3 class="card-title">@entry.Title</h3>
                    <div class="card-toolbar">
                        <a href="/admin/system/news/edit/@(entry.Id)">
                            <button class="btn btn-sm btn-light me-4">
                                <TL>Edit</TL>
                            </button>
                        </a>

                        <WButton CssClasses="btn btn-sm btn-light me-4"
                                 Text="@SmartTranslateService.Translate("Delete")"
                                 WorkingText="@SmartTranslateService.Translate("Deleting...")"
                                 OnClick="() => Delete(entry)">
                        </WButton>

                        <span class="text-gray-600 fw-semibold">@(Formatter.FormatDateOnly(entry.Date))</span>
                    </div>
                </div>
                <div class="card-body">
                    @{
                        var html = (MarkupString)Markdown.ToHtml(entry.Markdown);
                    }

                    @(html)
                </div>
            </div>
        }
    </LazyLoader>
</OnlyAdmin>

@code
{
    private NewsEntry[] Entries;

    private LazyLoader LazyLoader;
    private FileEditor FileEditor;

    private Task Load(LazyLoader loader)
    {
        Entries = NewsEntryRepository.Get().OrderByDescending(x => x.Date).ToArray();

        return Task.CompletedTask;
    }

    private async Task Delete(NewsEntry entry)
    {
        var confirm = await AlertService.ConfirmMath();

        if (!confirm) return;

        NewsEntryRepository.Delete(entry);

        await LazyLoader.Reload();
    }
}