using System.Xml.Linq;

namespace GsaEditor.Core.IO;

/// <summary>
/// Represents a single entry parsed from a .idx NML index file.
/// </summary>
public class GsaIndexEntry
{
    /// <summary>
    /// The file alias (relative path) of the entry.
    /// </summary>
    public string Id { get; set; } = string.Empty;

    /// <summary>
    /// Compression method: 0 = raw, 1 = zlib.
    /// </summary>
    public int Method { get; set; }

    /// <summary>
    /// Original (decompressed) size in bytes.
    /// </summary>
    public uint Length { get; set; }

    /// <summary>
    /// Compressed size in bytes.
    /// </summary>
    public uint CompressedLength { get; set; }

    /// <summary>
    /// Byte offset of the data block within the archive.
    /// </summary>
    public long Offset { get; set; }
}

/// <summary>
/// Parses .idx NML index files (XML-compatible format) into a list of <see cref="GsaIndexEntry"/>.
/// </summary>
public static class GsaIndexReader
{
    /// <summary>
    /// Reads index entries from the specified .idx file.
    /// </summary>
    /// <param name="filePath">The path to the .idx file.</param>
    /// <returns>A list of parsed index entries.</returns>
    public static List<GsaIndexEntry> Read(string filePath)
    {
        var doc = XDocument.Load(filePath);
        var entries = new List<GsaIndexEntry>();

        var root = doc.Root;
        if (root == null || root.Name.LocalName != "Index")
            return entries;

        foreach (var entryEl in root.Elements("Entry"))
        {
            var entry = new GsaIndexEntry
            {
                Id = entryEl.Element("Id")?.Value ?? string.Empty,
                Method = int.TryParse(entryEl.Element("Method")?.Value, out var m) ? m : 0,
                Length = uint.TryParse(entryEl.Element("Len")?.Value, out var l) ? l : 0,
                CompressedLength = uint.TryParse(entryEl.Element("CompLen")?.Value, out var cl) ? cl : 0,
                Offset = long.TryParse(entryEl.Element("Offset")?.Value, out var o) ? o : 0
            };
            entries.Add(entry);
        }

        return entries;
    }
}
