using System.Text;

namespace GsaEditor.Helpers;

/// <summary>
/// Produces a classic hex + ASCII dump string from a byte array.
/// </summary>
public static class HexDumper
{
    /// <summary>
    /// Formats a byte array as a hex dump with offset, hex values, and printable ASCII characters.
    /// </summary>
    /// <param name="data">The data to dump.</param>
    /// <param name="maxBytes">Maximum number of bytes to include in the dump.</param>
    /// <returns>A formatted hex dump string.</returns>
    public static string Dump(byte[] data, int maxBytes = 512)
    {
        var sb = new StringBuilder();
        int length = Math.Min(data.Length, maxBytes);
        const int bytesPerLine = 16;

        for (int offset = 0; offset < length; offset += bytesPerLine)
        {
            // Offset column
            sb.Append($"{offset:X8}  ");

            int lineLen = Math.Min(bytesPerLine, length - offset);

            // Hex columns
            for (int i = 0; i < bytesPerLine; i++)
            {
                if (i < lineLen)
                    sb.Append($"{data[offset + i]:X2} ");
                else
                    sb.Append("   ");

                if (i == 7) sb.Append(' ');
            }

            sb.Append(' ');

            // ASCII column
            for (int i = 0; i < lineLen; i++)
            {
                byte b = data[offset + i];
                sb.Append(b >= 0x20 && b < 0x7F ? (char)b : '.');
            }

            sb.AppendLine();
        }

        if (data.Length > maxBytes)
        {
            sb.AppendLine($"... ({data.Length - maxBytes} more bytes)");
        }

        return sb.ToString();
    }
}
