@page "/reservations"
@attribute [Microsoft.AspNetCore.Authorization.Authorize]
@rendermode RenderMode.InteractiveServer
@using Microsoft.EntityFrameworkCore
@using ZB.MOM.WW.OtOpcUa.Configuration
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@inject IDbContextFactory<OtOpcUaConfigDbContext> DbFactory

<div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="mb-0">External ID reservations</h4>
</div>

@if (_rows is null)
{
    <p>Loading…</p>
}
else
{
    <section class="panel notice rise" style="animation-delay:.02s">
        External IDs (ZTag, SAPID) are reserved fleet-wide via this table. Reservations bind a
        value to an Equipment's UUID so the ID can move with the equipment across cluster
        reshuffles without colliding with another cluster's equipment.
    </section>

    <section class="panel rise mt-3" style="animation-delay:.08s">
        <div class="panel-head">@_rows.Count reservation@(_rows.Count == 1 ? "" : "s")</div>
        @if (_rows.Count == 0)
        {
            <div style="padding:1rem" class="text-muted">No reservations yet.</div>
        }
        else
        {
            <div class="table-wrap">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Kind</th>
                            <th>Value</th>
                            <th>Equipment UUID</th>
                            <th>Cluster</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var r in _rows)
                        {
                            <tr>
                                <td><span class="chip chip-idle">@r.Kind</span></td>
                                <td><span class="mono">@r.Value</span></td>
                                <td><span class="mono small">@r.EquipmentUuid</span></td>
                                <td><span class="mono small">@r.ClusterId</span></td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        }
    </section>
}

@code {
    private List<ExternalIdReservation>? _rows;

    protected override async Task OnInitializedAsync()
    {
        await using var db = await DbFactory.CreateDbContextAsync();
        _rows = await db.ExternalIdReservations.AsNoTracking()
            .OrderBy(r => r.Kind).ThenBy(r => r.Value)
            .ToListAsync();
    }
}
