package com.zivilon.cinder_loe.coremod;

import net.minecraft.launchwrapper.IClassTransformer;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;

public class LOTRSpawnListLinker implements IClassTransformer {

    @Override
    public byte[] transform(String name, String transformedName, byte[] basicClass) {
        if ("lotr.common.world.spawning.LOTRSpawnList".equals(transformedName)) {
            System.out.println("[CinderLoE] Linking CinderLoE spawn-lists to LOTRMod...");
            return addLinks(basicClass, "RED_DWARF", "LIMWAITH"); // Can add any number of items, append with comma
        }
        return basicClass;
    }

    private byte[] addLinks(byte[] classBytes, String... fieldNames) {
        ClassReader reader = new ClassReader(classBytes);
        ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);

        reader.accept(new ClassVisitor(Opcodes.ASM5, writer) {
            @Override
            public void visitEnd() {
                // Add each field specified in the fieldNames array
                for (String fieldName : fieldNames) {
                    addSpawnListLink(fieldName, cv);
                }
                super.visitEnd();
            }
        }, 0);

        return writer.toByteArray();
    }

    private void addSpawnListLink(String fieldName, ClassVisitor cv) {
        // Define the field with public static access, name from the parameter, and type net.minecraft.item.Item
        FieldVisitor fv = cv.visitField(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, fieldName, "Llotr/common/world/spawning/LOTRSpawnList;", null, null);
        if (fv != null) {
            fv.visitEnd();
        }
    }
}