@page "/clusters/{ClusterId}/drivers/new/galaxy"
@attribute [Microsoft.AspNetCore.Authorization.Authorize]
@rendermode RenderMode.InteractiveServer
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.EntityFrameworkCore
@using ZB.MOM.WW.OtOpcUa.AdminUI.Clients
@using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers
@using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers.Pickers
@using ZB.MOM.WW.OtOpcUa.Configuration
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config
@inject IDbContextFactory<OtOpcUaConfigDbContext> DbFactory
@inject NavigationManager Nav

<div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="mb-0">@(IsNew ? "New AVEVA Galaxy driver" : "Edit AVEVA Galaxy driver") &middot; <span class="mono">@ClusterId</span></h4>
    <a href="/clusters/@ClusterId/drivers" class="btn btn-outline-secondary btn-sm">Cancel</a>
</div>
<ClusterNav ClusterId="@ClusterId" ActiveTab="drivers" />

@if (!_loaded)
{
    <p>Loading&hellip;</p>
}
else if (!IsNew && _existing is null)
{
    <section class="panel notice rise" style="animation-delay:.02s">
        Driver instance <span class="mono">@DriverInstanceId</span> was not found in cluster <span class="mono">@ClusterId</span>.
    </section>
}
else
{
    <EditForm Model="_form" OnValidSubmit="SubmitAsync" FormName="galaxyDriverEdit">
        <DataAnnotationsValidator />
        <DriverFormShell IsNew="IsNew" Busy="_busy" Error="@_error"
                         CancelHref="@($"/clusters/{ClusterId}/drivers")"
                         OnDelete="@(IsNew ? null : (EventCallback?)EventCallback.Factory.Create(this, DeleteAsync))">

            <DriverIdentitySection Model="_identityModel" Namespaces="_namespaces" IsNew="IsNew" ShowDriverType="false" />

            @if (!IsNew && !string.IsNullOrEmpty(DriverInstanceId))
            {
                <DriverStatusPanel DriverInstanceId="@DriverInstanceId" Enabled="@_identityModel.Enabled" />
            }

            <div class="mt-2 mb-3">
                <DriverTestConnectButton DriverType="@DriverTypeKey"
                                         GetConfigJson="@SerializeCurrentConfig"
                                         TimeoutSeconds="@_form.Galaxy.ProbeTimeoutSeconds" />
                <button type="button" class="btn btn-sm btn-outline-secondary mt-2"
                        @onclick="@(() => _showPicker = true)">
                    Pick address
                </button>
            </div>

            <DriverTagPicker @bind-Visible="_showPicker"
                             Title="Galaxy address"
                             CurrentAddress="@_pickedAddress"
                             OnPickAddress="@OnAddressPicked">
                <GalaxyAddressPickerBody CurrentAddress="@_pickedAddress"
                                         CurrentAddressChanged="@((s) => _pickedAddress = s)"
                                         GetConfigJson="@SerializeCurrentConfig" />
            </DriverTagPicker>

            @* mxaccessgw connection *@
            <section class="panel rise mt-3" style="animation-delay:.06s">
                <div class="panel-head">mxaccessgw connection</div>
                <div style="padding:1rem">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Gateway endpoint</label>
                            <InputText @bind-Value="_form.Galaxy.GatewayEndpoint" class="form-control form-control-sm mono"
                                       placeholder="https://localhost:5001" />
                            <div class="form-text">gRPC endpoint of the mxaccessgw process.</div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">API key secret ref</label>
                            <InputText @bind-Value="_form.Galaxy.GatewayApiKeySecretRef" class="form-control form-control-sm mono"
                                       placeholder="env:MX_API_KEY" />
                            <div class="form-text">Forms: <code>env:NAME</code>, <code>file:PATH</code>, <code>dev:KEY</code>. Cleartext is accepted but triggers a startup warning.</div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-check form-switch mt-4">
                                <InputCheckbox @bind-Value="_form.Galaxy.GatewayUseTls" class="form-check-input" id="gwTls" />
                                <label class="form-check-label" for="gwTls">Use TLS</label>
                            </div>
                        </div>
                        <div class="col-md-5">
                            <label class="form-label">CA certificate path (optional)</label>
                            <InputText @bind-Value="_form.Galaxy.GatewayCaCertificatePath" class="form-control form-control-sm mono"
                                       placeholder="C:\certs\ca.pem" />
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Connect timeout (s)</label>
                            <InputNumber @bind-Value="_form.Galaxy.GatewayConnectTimeoutSeconds" class="form-control form-control-sm" />
                            <div class="form-text">Default 10 s.</div>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Call timeout (s)</label>
                            <InputNumber @bind-Value="_form.Galaxy.GatewayDefaultCallTimeoutSeconds" class="form-control form-control-sm" />
                            <div class="form-text">Default 30 s.</div>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Stream timeout (s, 0 = unlimited)</label>
                            <InputNumber @bind-Value="_form.Galaxy.GatewayStreamTimeoutSeconds" class="form-control form-control-sm" />
                            <div class="form-text">Default 0 (lifetime of driver).</div>
                        </div>
                    </div>
                </div>
            </section>

            @* MXAccess *@
            <section class="panel rise mt-3" style="animation-delay:.08s">
                <div class="panel-head">MXAccess</div>
                <div style="padding:1rem">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label">Client name</label>
                            <InputText @bind-Value="_form.Galaxy.MxClientName" class="form-control form-control-sm"
                                       placeholder="OtOpcUa-Primary" />
                            <div class="form-text">Must be unique per OtOpcUa instance — redundancy pairs each get a distinct name.</div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Publishing interval (ms)</label>
                            <InputNumber @bind-Value="_form.Galaxy.MxPublishingIntervalMs" class="form-control form-control-sm" />
                            <div class="form-text">Default 1000 ms.</div>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Write user ID</label>
                            <InputNumber @bind-Value="_form.Galaxy.MxWriteUserId" class="form-control form-control-sm" />
                            <div class="form-text">0 = anonymous.</div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Event pump channel capacity</label>
                            <InputNumber @bind-Value="_form.Galaxy.MxEventPumpChannelCapacity" class="form-control form-control-sm" />
                            <div class="form-text">Default 50000. Raise if events.dropped appears.</div>
                        </div>
                    </div>
                </div>
            </section>

            @* Repository *@
            <section class="panel rise mt-3" style="animation-delay:.10s">
                <div class="panel-head">Galaxy repository</div>
                <div style="padding:1rem">
                    <div class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">Discover page size</label>
                            <InputNumber @bind-Value="_form.Galaxy.RepositoryDiscoverPageSize" class="form-control form-control-sm" />
                            <div class="form-text">Default 5000 objects per page.</div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-check form-switch mt-4">
                                <InputCheckbox @bind-Value="_form.Galaxy.RepositoryWatchDeployEvents" class="form-check-input" id="watchDeploy" />
                                <label class="form-check-label" for="watchDeploy">Watch deploy events</label>
                            </div>
                            <div class="form-text mt-0">Triggers address-space rebuild on Galaxy re-deploy.</div>
                        </div>
                    </div>
                </div>
            </section>

            @* Reconnect *@
            <section class="panel rise mt-3" style="animation-delay:.12s">
                <div class="panel-head">Reconnect backoff</div>
                <div style="padding:1rem">
                    <div class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">Initial backoff (ms)</label>
                            <InputNumber @bind-Value="_form.Galaxy.ReconnectInitialBackoffMs" class="form-control form-control-sm" />
                            <div class="form-text">Default 500 ms.</div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Max backoff (ms)</label>
                            <InputNumber @bind-Value="_form.Galaxy.ReconnectMaxBackoffMs" class="form-control form-control-sm" />
                            <div class="form-text">Default 30000 ms.</div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-check form-switch mt-4">
                                <InputCheckbox @bind-Value="_form.Galaxy.ReconnectReplayOnSessionLost" class="form-check-input" id="replayOnLost" />
                                <label class="form-check-label" for="replayOnLost">Replay subscriptions on session lost</label>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            @* Diagnostics *@
            <section class="panel rise mt-3" style="animation-delay:.14s">
                <div class="panel-head">Diagnostics</div>
                <div style="padding:1rem">
                    <div class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">Admin UI probe timeout (seconds)</label>
                            <InputNumber @bind-Value="_form.Galaxy.ProbeTimeoutSeconds" class="form-control form-control-sm" />
                            <div class="form-text">Max 60. Used by Test Connect. Default 30.</div>
                        </div>
                    </div>
                </div>
            </section>

            <DriverResilienceSection @bind-ResilienceConfig="_form.ResilienceConfig" />
        </DriverFormShell>
    </EditForm>
}

@code {
    [Parameter] public string ClusterId { get; set; } = "";
    [Parameter] public string? DriverInstanceId { get; set; }

    private const string DriverTypeKey = "GalaxyMxGateway";

    private bool IsNew => string.IsNullOrEmpty(DriverInstanceId);

    private static readonly System.Text.Json.JsonSerializerOptions _jsonOpts = new()
    {
        PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase,
        PropertyNameCaseInsensitive = true,
        UnmappedMemberHandling = System.Text.Json.Serialization.JsonUnmappedMemberHandling.Skip,
        WriteIndented = false,
    };

    private FormModel _form = new();
    private DriverIdentitySection.DriverIdentityModel _identityModel = new() { DriverType = DriverTypeKey };
    private DriverInstance? _existing;
    private List<Namespace> _namespaces = new();
    private bool _loaded;
    private bool _busy;
    private string? _error;

    // Address picker state
    private bool _showPicker;
    private string _pickedAddress = "";

    private void OnAddressPicked(string address) => _pickedAddress = address;

    protected override async Task OnInitializedAsync()
    {
        await using var db = await DbFactory.CreateDbContextAsync();
        _namespaces = await db.Namespaces.AsNoTracking()
            .Where(n => n.ClusterId == ClusterId)
            .OrderBy(n => n.NamespaceId)
            .ToListAsync();

        if (IsNew)
        {
            _identityModel = new()
            {
                DriverInstanceId = "",
                Name = "",
                DriverType = DriverTypeKey,
                NamespaceId = _namespaces.FirstOrDefault()?.NamespaceId ?? "",
                Enabled = true,
            };
            _form = new FormModel();
        }
        else
        {
            _existing = await db.DriverInstances.AsNoTracking()
                .FirstOrDefaultAsync(d => d.ClusterId == ClusterId && d.DriverInstanceId == DriverInstanceId);
            if (_existing is not null)
            {
                _identityModel = new()
                {
                    DriverInstanceId = _existing.DriverInstanceId,
                    Name = _existing.Name,
                    DriverType = _existing.DriverType,
                    NamespaceId = _existing.NamespaceId,
                    Enabled = _existing.Enabled,
                };
                var opts = TryDeserialize(_existing.DriverConfig) ?? CreateDefaultOptions();
                _form = new FormModel();
                _form.Galaxy = GalaxyFormModel.FromRecord(opts);
                _form.ResilienceConfig = _existing.ResilienceConfig;
                _form.RowVersion = _existing.RowVersion;
            }
        }
        _loaded = true;
    }

    private static GalaxyDriverOptions CreateDefaultOptions() => new(
        Gateway: new GalaxyGatewayOptions("https://localhost:5001", "env:MX_API_KEY"),
        MxAccess: new GalaxyMxAccessOptions("OtOpcUa"),
        Repository: new GalaxyRepositoryOptions(),
        Reconnect: new GalaxyReconnectOptions());

    private async Task SubmitAsync()
    {
        _busy = true; _error = null;
        try
        {
            var opts = _form.Galaxy.ToRecord();
            var configJson = System.Text.Json.JsonSerializer.Serialize(opts, _jsonOpts);
            await using var db = await DbFactory.CreateDbContextAsync();
            if (IsNew)
            {
                if (await db.DriverInstances.AnyAsync(d => d.DriverInstanceId == _identityModel.DriverInstanceId))
                {
                    _error = $"Driver instance '{_identityModel.DriverInstanceId}' already exists."; return;
                }
                db.DriverInstances.Add(new DriverInstance
                {
                    DriverInstanceId = _identityModel.DriverInstanceId,
                    ClusterId = ClusterId,
                    NamespaceId = _identityModel.NamespaceId,
                    Name = _identityModel.Name,
                    DriverType = DriverTypeKey,
                    Enabled = _identityModel.Enabled,
                    DriverConfig = configJson,
                    ResilienceConfig = string.IsNullOrWhiteSpace(_form.ResilienceConfig) ? null : _form.ResilienceConfig,
                });
            }
            else
            {
                var entity = await db.DriverInstances.FirstOrDefaultAsync(
                    d => d.ClusterId == ClusterId && d.DriverInstanceId == DriverInstanceId);
                if (entity is null) { _error = "Row no longer exists."; return; }
                db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
                entity.NamespaceId = _identityModel.NamespaceId;
                entity.Name = _identityModel.Name;
                entity.Enabled = _identityModel.Enabled;
                entity.DriverConfig = configJson;
                entity.ResilienceConfig = string.IsNullOrWhiteSpace(_form.ResilienceConfig) ? null : _form.ResilienceConfig;
            }
            await db.SaveChangesAsync();
            Nav.NavigateTo($"/clusters/{ClusterId}/drivers");
        }
        catch (DbUpdateConcurrencyException)
        {
            _error = "Another user changed this driver instance while you were editing. Reload to see the latest values, then re-apply your changes.";
        }
        catch (Exception ex) { _error = ex.Message; }
        finally { _busy = false; }
    }

    private async Task DeleteAsync()
    {
        if (IsNew) return;
        _busy = true; _error = null;
        try
        {
            await using var db = await DbFactory.CreateDbContextAsync();
            var entity = await db.DriverInstances.FirstOrDefaultAsync(
                d => d.ClusterId == ClusterId && d.DriverInstanceId == DriverInstanceId);
            if (entity is null) { Nav.NavigateTo($"/clusters/{ClusterId}/drivers"); return; }
            db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
            db.DriverInstances.Remove(entity);
            await db.SaveChangesAsync();
            Nav.NavigateTo($"/clusters/{ClusterId}/drivers");
        }
        catch (DbUpdateConcurrencyException)
        {
            _error = "Another user changed this driver instance while you were viewing it. Reload before deleting.";
        }
        catch (Exception ex)
        {
            _error = $"Delete failed: {ex.Message}. (Likely because equipment/tags still reference this driver — remove them first.)";
        }
        finally { _busy = false; }
    }

    private string SerializeCurrentConfig()
        => System.Text.Json.JsonSerializer.Serialize(_form.Galaxy.ToRecord(), _jsonOpts);

    private static GalaxyDriverOptions? TryDeserialize(string json)
    {
        try { return System.Text.Json.JsonSerializer.Deserialize<GalaxyDriverOptions>(json, _jsonOpts); }
        catch { return null; }
    }

    public sealed class FormModel
    {
        public GalaxyFormModel Galaxy { get; set; } = new();
        public string? ResilienceConfig { get; set; }
        public byte[] RowVersion { get; set; } = [];
    }

    /// <summary>
    ///     Mutable flat mirror of <see cref="GalaxyDriverOptions"/> and its nested records.
    ///     All positional-record fields are flattened with a section prefix to avoid name
    ///     collisions. <see cref="FromRecord"/> / <see cref="ToRecord"/> handle translation.
    /// </summary>
    public sealed class GalaxyFormModel
    {
        // GalaxyGatewayOptions
        public string GatewayEndpoint { get; set; } = "https://localhost:5001";
        public string GatewayApiKeySecretRef { get; set; } = "env:MX_API_KEY";
        public bool GatewayUseTls { get; set; } = true;
        public string? GatewayCaCertificatePath { get; set; }
        public int GatewayConnectTimeoutSeconds { get; set; } = 10;
        public int GatewayDefaultCallTimeoutSeconds { get; set; } = 30;
        public int GatewayStreamTimeoutSeconds { get; set; } = 0;

        // GalaxyMxAccessOptions
        public string MxClientName { get; set; } = "OtOpcUa";
        public int MxPublishingIntervalMs { get; set; } = 1000;
        public int MxWriteUserId { get; set; } = 0;
        public int MxEventPumpChannelCapacity { get; set; } = 50_000;

        // GalaxyRepositoryOptions
        public int RepositoryDiscoverPageSize { get; set; } = 5000;
        public bool RepositoryWatchDeployEvents { get; set; } = true;

        // GalaxyReconnectOptions
        public int ReconnectInitialBackoffMs { get; set; } = 500;
        public int ReconnectMaxBackoffMs { get; set; } = 30_000;
        public bool ReconnectReplayOnSessionLost { get; set; } = true;

        // GalaxyDriverOptions top-level
        public int ProbeTimeoutSeconds { get; set; } = 30;

        public static GalaxyFormModel FromRecord(GalaxyDriverOptions r)
        {
            // Null-coalesce each nested record to its default so that persisted configs
            // that pre-date a section (e.g. no Reconnect key, or PascalCase keys that
            // don't match the camelCase deserializer) don't cause a NullReferenceException.
            var gw   = r.Gateway    ?? new GalaxyGatewayOptions("https://localhost:5001", "env:MX_API_KEY");
            var mx   = r.MxAccess   ?? new GalaxyMxAccessOptions("OtOpcUa");
            var repo = r.Repository ?? new GalaxyRepositoryOptions();
            var rc   = r.Reconnect  ?? new GalaxyReconnectOptions();
            return new()
            {
                GatewayEndpoint = gw.Endpoint,
                GatewayApiKeySecretRef = gw.ApiKeySecretRef,
                GatewayUseTls = gw.UseTls,
                GatewayCaCertificatePath = gw.CaCertificatePath,
                GatewayConnectTimeoutSeconds = gw.ConnectTimeoutSeconds,
                GatewayDefaultCallTimeoutSeconds = gw.DefaultCallTimeoutSeconds,
                GatewayStreamTimeoutSeconds = gw.StreamTimeoutSeconds,
                MxClientName = mx.ClientName,
                MxPublishingIntervalMs = mx.PublishingIntervalMs,
                MxWriteUserId = mx.WriteUserId,
                MxEventPumpChannelCapacity = mx.EventPumpChannelCapacity,
                RepositoryDiscoverPageSize = repo.DiscoverPageSize,
                RepositoryWatchDeployEvents = repo.WatchDeployEvents,
                ReconnectInitialBackoffMs = rc.InitialBackoffMs,
                ReconnectMaxBackoffMs = rc.MaxBackoffMs,
                ReconnectReplayOnSessionLost = rc.ReplayOnSessionLost,
                ProbeTimeoutSeconds = r.ProbeTimeoutSeconds,
            };
        }

        public GalaxyDriverOptions ToRecord() => new(
            Gateway: new GalaxyGatewayOptions(
                Endpoint: GatewayEndpoint,
                ApiKeySecretRef: GatewayApiKeySecretRef,
                UseTls: GatewayUseTls,
                CaCertificatePath: string.IsNullOrWhiteSpace(GatewayCaCertificatePath) ? null : GatewayCaCertificatePath,
                ConnectTimeoutSeconds: GatewayConnectTimeoutSeconds,
                DefaultCallTimeoutSeconds: GatewayDefaultCallTimeoutSeconds,
                StreamTimeoutSeconds: GatewayStreamTimeoutSeconds),
            MxAccess: new GalaxyMxAccessOptions(
                ClientName: MxClientName,
                PublishingIntervalMs: MxPublishingIntervalMs,
                WriteUserId: MxWriteUserId,
                EventPumpChannelCapacity: MxEventPumpChannelCapacity),
            Repository: new GalaxyRepositoryOptions(
                DiscoverPageSize: RepositoryDiscoverPageSize,
                WatchDeployEvents: RepositoryWatchDeployEvents),
            Reconnect: new GalaxyReconnectOptions(
                InitialBackoffMs: ReconnectInitialBackoffMs,
                MaxBackoffMs: ReconnectMaxBackoffMs,
                ReplayOnSessionLost: ReconnectReplayOnSessionLost))
        {
            ProbeTimeoutSeconds = ProbeTimeoutSeconds,
        };
    }
}
