package com.zivilon.cindercore.coremod;

import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileOutputStream;


public class PacketWindowItemsTransformer implements IClassTransformer {
    @Override
    public byte[] transform(String name, String transformedName, byte[] classBytes) {
        if (transformedName.equals("net.minecraft.network.play.server.S30PacketWindowItems")) {
            System.out.println("Transforming: " + transformedName);
            ClassReader reader = new ClassReader(classBytes);
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
            reader.accept(new ClassVisitor(Opcodes.ASM5, writer) {
                @Override
                public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
                    MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
                    if (name.equals("func_148911_c") || name.equals("func_148910_d")) {
                        return new MethodVisitor(Opcodes.ASM5, mv) {
                            @Override
                            public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
                                if (desc.equals("Lcpw/mods/fml/relauncher/SideOnly;")) {
                                    return null;
                                }
                                return super.visitAnnotation(desc, visible);
                            }
                        };
                    }
                    return mv;
                }
            }, 0);
            byte[] transformedBytes = writer.toByteArray();
            writeToFile(transformedBytes, "S30PacketWindowItems.class");
            return transformedBytes;
        }
        return classBytes;
    }

    private void writeToFile(byte[] data, String fileName) {
        try (FileOutputStream out = new FileOutputStream(fileName)) {
            out.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
