@page "/clusters/{ClusterId}/drivers"
@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">Drivers &middot; <span class="mono">@ClusterId</span></h4>
    <a href="/clusters/@ClusterId/drivers/new" class="btn btn-primary btn-sm">New driver</a>
</div>

<ClusterNav ClusterId="@ClusterId" ActiveTab="drivers" />

@if (_rows is null)
{
    <p>Loading…</p>
}
else
{
    <section class="panel rise mt-3" style="animation-delay:.08s">
        <div class="panel-head">@_rows.Count driver instance@(_rows.Count == 1 ? "" : "s")</div>
        @if (_rows.Count == 0)
        {
            <div style="padding:1rem" class="text-muted">No driver instances for this cluster.</div>
        }
        else
        {
            @foreach (var d in _rows)
            {
                <details style="border-top:1px solid var(--rule)">
                    <summary style="padding:.75rem 1rem;cursor:pointer">
                        <span class="mono">@d.DriverInstanceId</span>
                        &middot; <span>@d.Name</span>
                        &middot; <span class="chip chip-idle ms-1">@d.DriverType</span>
                        @if (!d.Enabled) { <span class="chip chip-idle ms-1">Disabled</span> }
                        <span class="text-muted small ms-2">ns=@d.NamespaceId</span>
                    </summary>
                    <div style="padding:0 1rem 1rem">
                        <div class="d-flex mb-2">
                            <a href="/clusters/@ClusterId/drivers/@d.DriverInstanceId" class="btn btn-sm btn-outline-primary">Edit</a>
                        </div>
                        <pre class="mono small" style="background:var(--surface-2);padding:1rem;border-radius:4px;overflow:auto">@FormatJson(d.DriverConfig)</pre>
                        @if (!string.IsNullOrWhiteSpace(d.ResilienceConfig))
                        {
                            <div class="text-muted small mt-2">Resilience overrides:</div>
                            <pre class="mono small" style="background:var(--surface-2);padding:1rem;border-radius:4px;overflow:auto">@FormatJson(d.ResilienceConfig)</pre>
                        }
                    </div>
                </details>
            }
        }
    </section>
}

@code {
    [Parameter] public string ClusterId { get; set; } = "";
    private List<DriverInstance>? _rows;

    protected override async Task OnInitializedAsync()
    {
        await using var db = await DbFactory.CreateDbContextAsync();
        _rows = await db.DriverInstances.AsNoTracking()
            .Where(d => d.ClusterId == ClusterId)
            .OrderBy(d => d.DriverInstanceId)
            .ToListAsync();
    }

    private static string FormatJson(string raw)
    {
        if (string.IsNullOrWhiteSpace(raw)) return "";
        try
        {
            using var doc = System.Text.Json.JsonDocument.Parse(raw);
            return System.Text.Json.JsonSerializer.Serialize(doc.RootElement,
                new System.Text.Json.JsonSerializerOptions { WriteIndented = true });
        }
        catch
        {
            return raw;
        }
    }
}
