@using ZB.MOM.WW.OtOpcUa.AdminUI.Uns.TagEditors
@using ZB.MOM.WW.OtOpcUa.Driver.AbCip

<div class="row g-2">
    <div class="col-md-4"><label class="form-label">Device host</label>
        <input class="form-control form-control-sm mono" value="@_m.DeviceHostAddress" placeholder="ab://gateway[:port]/cip-path" @onchange="@(e => Update(() => _m.DeviceHostAddress = e.Value?.ToString() ?? string.Empty))" /></div>
    <div class="col-md-5"><label class="form-label">Tag path</label>
        <input class="form-control form-control-sm mono" value="@_m.TagPath" placeholder="e.g. Motor1.Speed" @onchange="@(e => Update(() => _m.TagPath = e.Value?.ToString() ?? string.Empty))" /></div>
    <div class="col-md-3"><label class="form-label">Data type</label>
        <select class="form-select form-select-sm" value="@_m.DataType" @onchange="@(e => Update(() => _m.DataType = ParseEnum(e.Value, AbCipDataType.DInt)))">
            @foreach (var v in Enum.GetValues<AbCipDataType>()) { <option value="@v">@v</option> }
        </select></div>
</div>

@code {
    [Parameter] public string? ConfigJson { get; set; }
    [Parameter] public EventCallback<string> ConfigJsonChanged { get; set; }

    private AbCipTagConfigModel _m = new();
    private string? _lastConfigJson;

    // Re-parse only when the incoming JSON actually changes, so an unrelated parent re-render
    // (Blazor Server live-status pushes do this) can't reset the user's in-progress edits.
    protected override void OnParametersSet()
    {
        if (ConfigJson == _lastConfigJson) { return; }
        _lastConfigJson = ConfigJson;
        _m = AbCipTagConfigModel.FromJson(ConfigJson);
    }

    // TryParse so a bad/empty change value can never throw into the Blazor circuit — it falls back.
    private static TEnum ParseEnum<TEnum>(object? v, TEnum fallback) where TEnum : struct, Enum
        => Enum.TryParse<TEnum>(v?.ToString(), out var r) ? r : fallback;

    private async Task Update(Action apply)
    {
        apply();
        await ConfigJsonChanged.InvokeAsync(_m.ToJson());
    }
}
