package shadersmod.transform;

import java.util.Iterator;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import static org.objectweb.asm.Opcodes.*;

import org.objectweb.asm.commons.Remapper;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.util.Textifier;
import org.objectweb.asm.util.TraceMethodVisitor;


import net.minecraft.launchwrapper.IClassTransformer;
import shadersmod.client.SVertexFormat;
import shadersmod.common.SMCLog;

// for VboRenderList

public class SMCCTVboRenderList implements IClassTransformer {

	@Override
	public byte[] transform(String par1, String par2, byte[] par3) {
		SMCLog.fine("transforming %s %s",par1,par2);
		ClassReader cr = new ClassReader(par3);
		ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
		CVTransform cv = new CVTransform(cw);
		cr.accept(cv,0);
		return cw.toByteArray();
	}
	
	private static final int vertexSize = SVertexFormat.vertexSizeBlock;

	private static class CVTransform extends ClassVisitor
	{
		String classname;
		public CVTransform(ClassVisitor cv)
		{
			super(Opcodes.ASM4, cv);		
		}

		@Override
		public void visit(int version, int access, String name,
				String signature, String superName, String[] interfaces) {
			classname = name;
			//SMCLog.info(" class %s",name);
			cv.visit(version, access, name, signature, superName, interfaces);
		}

		@Override
		public MethodVisitor visitMethod(int access, String name, String desc,
				String signature, String[] exceptions) 
		{
			if (Names.vboRenderList_setupArrayPointers.equalsNameDesc(name,desc))
			{
				SMCLog.finer("  patch method %s.%s%s",classname,name,desc);
				return new MVsetupArrayPointers(cv.visitMethod(access, name, desc, signature, exceptions));
			}
			return cv.visitMethod(access, name, desc, signature, exceptions);
		}
		
	}

	private static class MVsetupArrayPointers extends MethodVisitor
	{
		public MVsetupArrayPointers(MethodVisitor mv) {
			super(Opcodes.ASM4, null);
			mv.visitCode();
			mv.visitMethodInsn(INVOKESTATIC, "shadersmod/client/ShadersRender", "setupArrayPointersVbo", "()V");
			mv.visitInsn(RETURN);
			mv.visitMaxs(0, 1);
			mv.visitEnd();
		}
		
	}
}
