package com.gradle.ares

import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes

/**
 * Created by Glen on 2017/2/8.
 */

public class MethodAgentVisitor extends MethodBaseVisitor {

    public static List<MethodModel> Modify = new ArrayList<>();

    static {
        Modify.add(new MethodModel("onClick", "(Landroid/view/View;)V", 1))//view
        Modify.add(new MethodModel("onClick", "(Landroid/content/DialogInterface;I)V", 2))//dialog
        Modify.add(new MethodModel("onItemClick", "(Landroid/widget/AdapterView;Landroid/view/View;IJ)V", 4))
//list view
        Modify.add(new MethodModel("onTabSelected", "(Landroid/support/design/widget/TabLayout\$Tab;)V", 1))
//design lib tab layout
        Modify.add(new MethodModel("onCheckedChanged", "(Landroid/widget/CompoundButton;Z)V", 2))
//check box
    }

    public
    static MethodModel getAgent(int access, String className, String superName, String name, String desc) {
        for (MethodModel item : Modify) {
            if (item.name == name && item.desc == desc) {
                item.access = access
                item.className = className
                item.superName = superName
                return item
            }
        }
        return null
    }

    public MethodAgentVisitor(MethodVisitor mv, MethodModel agent) {
        super(mv, agent)
    }

    @Override
    void visitCode() {
        super.visitCode()
        for (int i = 0; i < this.agent.count; i++) loadArg(i)
        visitMethodInsn(Opcodes.INVOKESTATIC, AresValue.AgentClass, this.agent.name + "Pre", this.agent.desc, false)
    }

    @Override
    public void visitInsn(int opcode) {
        if (opcode == Opcodes.RETURN) {
            for (int i = 0; i < this.agent.count; i++) loadArg(i)
            visitMethodInsn(Opcodes.INVOKESTATIC, AresValue.AgentClass, this.agent.name, this.agent.desc, false)
        }
        super.visitInsn(opcode);
    }
}
