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

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

/// <summary>Typed working model for a FOCAS (FANUC CNC) 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 FocasTagConfigModel
{
    /// <summary>Which device (<c>FocasDeviceOptions.HostAddress</c>) this tag lives on. Optional.</summary>
    public string DeviceHostAddress { get; set; } = "";

    /// <summary>Canonical FOCAS address string, e.g. <c>X0.0</c>, <c>R100</c>, <c>PARAM:1815/0</c>, <c>MACRO:500</c>. Required.</summary>
    public string Address { get; set; } = "";

    /// <summary>FOCAS atomic data type.</summary>
    public FocasDataType DataType { get; set; } = FocasDataType.Int32;

    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 FocasTagConfigModel FromJson(string? json)
    {
        var o = TagConfigJson.ParseOrNew(json);
        return new FocasTagConfigModel
        {
            DeviceHostAddress = TagConfigJson.GetString(o, "deviceHostAddress") ?? "",
            Address = TagConfigJson.GetString(o, "address") ?? "",
            DataType = TagConfigJson.GetEnum(o, "dataType", FocasDataType.Int32),
            _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>
    /// <returns>The serialised TagConfig JSON string.</returns>
    public string ToJson()
    {
        TagConfigJson.Set(_bag, "deviceHostAddress", string.IsNullOrWhiteSpace(DeviceHostAddress) ? null : DeviceHostAddress.Trim());
        TagConfigJson.Set(_bag, "address", Address.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>
    /// <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;
}
