using System.Xml.Linq;
using GsaEditor.Core.Models;

namespace GsaEditor.Core.IO;

/// <summary>
/// Writes a .idx NML index file from a <see cref="GsaArchive"/>.
/// The index file is XML-compatible and lists each entry with its alias, compression method,
/// sizes, and data offset for fast lookup without a full sequential scan.
/// </summary>
public static class GsaIndexWriter
{
    /// <summary>
    /// Writes the index file for the given archive to the specified path.
    /// </summary>
    /// <param name="archive">The archive whose entries will be indexed.</param>
    /// <param name="filePath">The output .idx file path.</param>
    public static void Write(GsaArchive archive, string filePath)
    {
        var doc = new XDocument(
            new XElement("Index",
                archive.Entries.Select(e =>
                    new XElement("Entry",
                        new XElement("Id", e.Alias),
                        new XElement("Method", e.IsCompressed ? 1 : 0),
                        new XElement("Len", e.OriginalLength),
                        new XElement("CompLen", e.CompressedLength),
                        new XElement("Offset", e.DataOffset)
                    )
                )
            )
        );

        doc.Save(filePath);
    }
}
