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 LOTRWeaponLinker implements IClassTransformer {

    @Override
    public byte[] transform(String name, String transformedName, byte[] basicClass) {
        if ("lotr.common.LOTRMod".equals(transformedName)) {
            System.out.println("[CinderLoE] Linking CinderLoE items to LOTRMod...");

            // Can add any number of items, append with comma
            return addLinks(basicClass,
                "spearRedDwarf", "crossbowRedDwarf", "swordRedDwarf", "battleaxeRedDwarf", "pikeRedDwarf", "daggerRedDwarf", "daggerRedDwarfPoisoned", "hammerRedDwarf",
                "radagastStaff", "alatarStaff", "pallandoStaff", "sarumanStaff", "maceWarlord", "sarumanWhiteStaff", "mouthofsauronSword",
                "spearLimwaith", "tridentLimwaith", "daggerLimwaith", "daggerLimwaithPoisoned", "truncheonLimwaith", "battleaxeLimwaith", "blowgunLimwaith",
                "frostblade", "spearsolidgold", "whip", "spearUnnamed", "welfRelic", "daggerVoid",
                "swordBree", "greatswordAngmar", "greatswordLindon", "greatswordDale", "greatswordNumenor",
                "maceArnor",
                "daggerAsh","bowAsh","hammerAsh","pikeAsh","battleaxeAsh","swordAsh","spearAsh", "staffAsh", "cleaver",
                "bowLurtz",
                "greatswordLight");
        }
        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) {
                    addItemLink(fieldName, cv);
                }
                super.visitEnd();
            }
        }, 0);

        return writer.toByteArray();
    }

    private void addItemLink(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, "Lnet/minecraft/item/Item;", null, null);
        if (fv != null) {
            fv.visitEnd();
        }
    }
}
