using System.Text;

namespace RobloxLegacy.Utilities;

public static class Patcher
{
    // this is insanely autistic
    // if you have a better way of doing it let me know
    public static void RenameImports(string filePath, List<string> oldNames, string newName)
    {
        var exeBytes = File.ReadAllBytes(filePath);
        foreach (var oldName in oldNames)
        {
            var oldNameBytes = Encoding.ASCII.GetBytes(oldName);
            var newNameBytes = Encoding.ASCII.GetBytes(newName);

            var oldNameLength = oldNameBytes.Length;
            var newNameLength = newNameBytes.Length;

            if (newNameLength > oldNameLength)
                throw new Exception("New name cannot be longer than old name");

            // scan the binary data for the old name
            for (var i = 0; i < exeBytes.Length - oldNameLength; i++)
            {
                var match = true;
                for (var j = 0; j < oldNameLength; j++)
                {
                    if (exeBytes[i + j] != oldNameBytes[j])
                    {
                        match = false;
                        break;
                    }
                }
                
                if (match) // if a match is found, replace it
                {
                    Array.Copy(newNameBytes, 0, exeBytes, i, newNameLength);
                    if (newNameLength < oldNameLength)
                    {
                        for (var j = newNameLength; j < oldNameLength; j++)
                        {
                            exeBytes[i + j] = 0;  // set remaining bytes to 0
                        }
                    }
                }
            }
        }
        File.WriteAllBytes(filePath, exeBytes);
    }
}