using System.Xml;

namespace aeqw89.tools.Publish;

internal class Project {
    public string Path { get; }
    private XmlDocument Document { get; }
    public List<PropertyGroup> PropertyGroups { get; }
    public List<ItemGroup> ItemGroups { get; }

    private Project(string path, XmlDocument doc) {
        Path = path;
        Document = doc;

        // Build PropertyGroups
        PropertyGroups = doc.DocumentElement!
            .SelectNodes("./PropertyGroup")!
            .OfType<XmlElement>()
            .Select(e => new PropertyGroup(e))
            .ToList();

        // Build ItemGroups (+ their Items)
        ItemGroups = doc.DocumentElement!
            .SelectNodes("./ItemGroup")!
            .OfType<XmlElement>()
            .Select(e => new ItemGroup(e))
            .ToList();

        // Ensure at least one ItemGroup exists (some csprojs omit it until first item is added)
        if (ItemGroups.Count == 0) {
            var ig = doc.CreateElement("ItemGroup", doc.DocumentElement!.NamespaceURI);
            doc.DocumentElement!.AppendChild(ig);
            ItemGroups.Add(new ItemGroup((XmlElement)ig));
        }
    }

    public static Project Load(string path) {
        var doc = new XmlDocument();
        doc.PreserveWhitespace = false;
        doc.Load(path);
        return new Project(path, doc);
    }

    public void Save() {
        var settings = new XmlWriterSettings {
            Indent = true,
            IndentChars = "    ",
            NewLineChars = Environment.NewLine,
            NewLineHandling = NewLineHandling.Replace
        };
        using var writer = XmlWriter.Create(Path, settings);
        Document.Save(writer);
    }
}