package shadersmod.transform;

import static org.objectweb.asm.Opcodes.*;

import java.util.HashMap;
import java.util.Map;

import net.minecraft.launchwrapper.IClassTransformer;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.InsnList;

import shadersmod.common.SMCLog;

public class DummyToAccessor 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, 0);
		CVTransform cv = new CVTransform(cw);
		cr.accept(cv,0);
		return cw.toByteArray();
	}

	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) {
			this.classname = name;
			//SMCLog.info(" class %s",name);
			super.visit(version, access, name, signature, superName, interfaces);
		}

		@Override
		public MethodVisitor visitMethod(int access, String name, String desc,
				String signature, String[] exceptions) 
		{
			return new MVShadersModClient(cv.visitMethod(access, name, desc, signature, exceptions));
		}
		
	}
	
	
	private static class MVShadersModClient extends MethodVisitor
	{
		public MVShadersModClient(MethodVisitor mv) {
			super(Opcodes.ASM4, mv);
		}

		@Override
		public void visitMethodInsn(int opcode, String owner, String name, String desc) {
			if (Names.dummy_.clasName.equals(owner)) {
				InsnList insnList = DummyData.mapDummyToInsnList.get(name);
				if (insnList != null)
					insnList.accept(mv);
				else 
					SMCLog.error("Unknown dummy function %s %s",name,desc);
				return;
			}
			super.visitMethodInsn(opcode, owner, name, desc);
		}
		
	}

}
