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

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

/// <summary>Typed working model for a Siemens S7 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 S7TagConfigModel
{
    /// <summary>S7 address string, e.g. <c>DB1.DBW0</c>, <c>M0.0</c>, <c>I0.0</c>, <c>QD4</c>. Required.</summary>
    public string Address { get; set; } = "";

    /// <summary>Logical data type — drives the underlying S7.Net read/write width.</summary>
    public S7DataType DataType { get; set; } = S7DataType.Int16;

    /// <summary>For <c>DataType = String</c>: S7-string max length (max 254).</summary>
    public int StringLength { get; set; }

    /// <summary>Optional writable flag (R2-11); <c>null</c> ⇒ omitted (driver default true), explicit
    /// <c>false</c> ⇒ read-only. Preserved across load→save.</summary>
    public bool? Writable { get; set; }

    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>
    /// <param name="json">The raw TagConfig JSON string, or null/empty for a fresh model.</param>
    /// <returns>The populated model, defaulted where fields are absent from <paramref name="json"/>.</returns>
    public static S7TagConfigModel FromJson(string? json)
    {
        var o = TagConfigJson.ParseOrNew(json);
        return new S7TagConfigModel
        {
            Address = TagConfigJson.GetString(o, "address") ?? "",
            DataType = TagConfigJson.GetEnum(o, "dataType", S7DataType.Int16),
            StringLength = TagConfigJson.GetInt(o, "stringLength"),
            Writable = TagConfigJson.GetBoolNullable(o, "writable"),
            _bag = o,
        };
    }

    /// <summary>Serialises this model back to a TagConfig JSON string, writing the exposed fields
    /// (enum as its name string) over the preserved key bag.</summary>
    /// <returns>The serialised TagConfig JSON string.</returns>
    public string ToJson()
    {
        TagConfigJson.Set(_bag, "address", Address.Trim());
        TagConfigJson.Set(_bag, "dataType", DataType);
        TagConfigJson.Set(_bag, "stringLength", StringLength);
        TagConfigJson.Set(_bag, "writable", Writable);
        return TagConfigJson.Serialize(_bag);
    }

    /// <summary>Validation hook; returns an error message or null when the model is valid.</summary>
    /// <returns>An error message describing the validation failure, or null when the model is valid.</returns>
    public string? Validate()
        => string.IsNullOrWhiteSpace(Address) ? "Address is required." : null;
}
