package com.lion328.xenonlauncher.patcher;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodNode;

import java.util.List;

public class StringReplaceFilePatcher implements FilePatcher
{

    private final String find;
    private final String replace;

    public StringReplaceFilePatcher(String find, String replace)
    {
        this.find = find;
        this.replace = replace;
    }

    @Override
    public byte[] patchFile(String name, byte[] original)
    {
        if (!name.endsWith(".class"))
        {
            return original;
        }

        ClassReader reader = new ClassReader(original);
        ClassNode node = new ClassNode();
        reader.accept(node, 0);

        List<FieldNode> fields = node.fields;
        for (FieldNode field : fields)
        {
            if (field.value instanceof String)
            {
                field.value = ((String) field.value).replace(find, replace);
            }
        }

        List<MethodNode> methods = node.methods;
        for (MethodNode method : methods)
        {
            InsnList insns = method.instructions;

            for (int i = 0; i < insns.size(); i++)
            {
                AbstractInsnNode insn = insns.get(i);

                if (!(insn instanceof LdcInsnNode))
                {
                    continue;
                }

                LdcInsnNode ldc = (LdcInsnNode) insn;

                if (!(ldc.cst instanceof String))
                {
                    continue;
                }

                ldc.cst = ((String) ldc.cst).replace(find, replace);
            }
        }

        ClassWriter writer = new ClassWriter(0);
        node.accept(writer);

        return writer.toByteArray();
    }
}

@@ -972,19 +972,8 @@
 List
-%3CFieldNode%3E
  fie
@@ -999,21 +999,16 @@
         
-for (
 FieldNod
@@ -1014,16 +1014,41 @@
 de field
+;%0A        for (Object obj
  : field
@@ -1052,32 +1052,170 @@
 elds)%0A        %7B%0A
+            if (!(obj instanceof FieldNode))%0A            %7B%0A                continue;%0A            %7D%0A%0A            field = (FieldNode) obj;%0A%0A
             if (
@@ -1377,20 +1377,8 @@
 List
-%3CMethodNode%3E
  met
@@ -1406,21 +1406,16 @@
         
-for (
 MethodNo
@@ -1427,29 +1427,195 @@
 thod
- : methods)%0A        %7B
+;%0A        for (Object obj : methods)%0A        %7B%0A            if (!(obj instanceof MethodNode))%0A            %7B%0A                continue;%0A            %7D%0A%0A            method = (MethodNode) obj;%0A
 %0A   

Fix warning in StringReplaceFilePatcher