using System.Text.Json.Nodes;
using ZB.MOM.WW.OtOpcUa.Driver.AbCip;

namespace ZB.MOM.WW.OtOpcUa.AdminUI.Uns.TagEditors;

/// <summary>Typed working model for an AB CIP / EtherNet-IP tag's TagConfig JSON (the driver-specific addressing/encoding
/// fields; name/writable live on the Tag entity). Preserves unrecognised JSON keys across a load→save.</summary>
public sealed class AbCipTagConfigModel
{
    /// <summary>Which device (<c>AbCipDeviceOptions.HostAddress</c>) this tag lives on. Optional.</summary>
    public string DeviceHostAddress { get; set; } = "";

    /// <summary>Logix symbolic path (controller or program scope). Required.</summary>
    public string TagPath { get; set; } = "";

    /// <summary>Logix atomic type, or <c>AbCipDataType.Structure</c> for UDT-typed tags.</summary>
    public AbCipDataType DataType { get; set; } = AbCipDataType.DInt;

    private JsonObject _bag = new();

    /// <summary>Loads a model from a TagConfig JSON string, defaulting any absent field and retaining
    /// every original key (so fields this editor doesn't expose survive a load→save).</summary>
    public static AbCipTagConfigModel FromJson(string? json)
    {
        var o = TagConfigJson.ParseOrNew(json);
        return new AbCipTagConfigModel
        {
            DeviceHostAddress = TagConfigJson.GetString(o, "deviceHostAddress") ?? "",
            TagPath = TagConfigJson.GetString(o, "tagPath") ?? "",
            DataType = TagConfigJson.GetEnum(o, "dataType", AbCipDataType.DInt),
            _bag = o,
        };
    }

    /// <summary>Serialises this model back to a TagConfig JSON string, writing the exposed fields
    /// (enum as its name string; the optional host address omitted when blank) over the preserved key bag.</summary>
    public string ToJson()
    {
        TagConfigJson.Set(_bag, "deviceHostAddress", string.IsNullOrWhiteSpace(DeviceHostAddress) ? null : DeviceHostAddress.Trim());
        TagConfigJson.Set(_bag, "tagPath", TagPath.Trim());
        TagConfigJson.Set(_bag, "dataType", DataType);
        return TagConfigJson.Serialize(_bag);
    }

    /// <summary>Validation hook; returns an error message or null when the model is valid.</summary>
    public string? Validate()
        => string.IsNullOrWhiteSpace(TagPath) ? "Tag path is required." : null;
}
