@page "/Settings/Tools"
@using LANCommander.Models;
@layout SettingsLayout
@inject IMessageService MessageService
@inject ArchiveService ArchiveService
@attribute [Authorize(Roles = "Administrator")]

<PageHeader Title="Tools" />

<div style="padding: 0 24px;">
    <h3>Recalculate File Sizes</h3>
    <p>
        Some file sizes are cached in the database. Click the button below to scan through all files and recalculate their size.
    </p>
    <Button Type="@ButtonType.Primary" OnClick="RecalculateFileSizes" Loading="RecalculatingFileSizes">Recalculate</Button>

    <Divider />

    <h3>Missing Archives</h3>
    <p>List and fix all archives that are missing their backing files.</p>
    <a href="/Settings/Tools/MissingArchives" class="ant-btn ant-btn-primary">View Missing Archives</a>

    <Divider />

    <h3>Orphaned Files</h3>
    <p>Find and delete any files that don't exist in the database and may be taking up unnecessary disk space.</p>
    <a href="/Settings/Tools/OrphanedFiles" class="ant-btn ant-btn-primary">View Orphaned Files</a>
</div>


@code {
    bool RecalculatingFileSizes = false;

    async Task RecalculateFileSizes()
    {
        RecalculatingFileSizes = true;

        StateHasChanged();

        var archives = await ArchiveService.Get();

        foreach (var archive in archives)
        {
            var path = ArchiveService.GetArchiveFileLocation(archive);

            if (File.Exists(path))
            {
                archive.CompressedSize = new FileInfo(path).Length;

                await ArchiveService.Update(archive);
            }
        }

        await MessageService.Success("File sizes recalculated!");

        RecalculatingFileSizes = false;
    }
}
