using System.Xml;

namespace aeqw89.tools.Publish;

internal class Item {
    public string ElementName { get; protected set; }
    public string Include {
        get => Node.GetAttribute("Include");
        set => Node.SetAttribute("Include", value);
    }

    public string Version {
        get => Node.GetAttribute("Version");
        set => Node.SetAttribute("Version", value);
    }
    
    public string? Value {
        get => Node.InnerText;
        set { Node.InnerText = value ?? string.Empty; }
    }
    public XmlElement Node { get; }

    protected Item(XmlElement node) {
        Node = node;
        ElementName = node.Name;
    }

    public static Item FromElement(XmlElement element) {
        return element.Name switch {
            "PackageReference" => new PackageReference(element),
            "ProjectReference" => new ProjectReference(element),
            "Content"          => new Content(element),
            _                  => new Item(element),
        };
    }

    public void AddChild(Item child) {
        var imported = Node.OwnerDocument!.ImportNode(child.Node, true);
        Node.AppendChild(imported);
    }

    public string? GetAttribute(string name) => Node.HasAttribute(name) ? Node.GetAttribute(name) : null;
    public void SetAttribute(string name, string? value) {
        if (value is null) {
            if (Node.HasAttribute(name)) Node.RemoveAttribute(name);
            return;
        }
        Node.SetAttribute(name, value);
    }
    
    public IEnumerable<Item> GetChildElements() {
        foreach (var e in Node.ChildNodes.OfType<XmlElement>())
            yield return new Item(e);
    }
}