package com.gh.gamecenter.plugin.transform

import javassist.ClassPool
import javassist.CtClass
import javassist.CtNewMethod
import javassist.bytecode.ClassFile
import java.io.BufferedInputStream
import java.io.DataInputStream
import java.io.InputStream

class RoomTransformer : Transformer {

    private val classPool = ClassPool.getDefault()

    override fun getModifyClassName(): String {
        return "InvalidationTracker\$1.class"
    }

    override fun modifyClass(filePath: String, inputStream: InputStream): CtClass? {
        if (filePath.contains(getModifyClassName())) {
            val classFile = ClassFile(DataInputStream(BufferedInputStream(inputStream)))
            val ctClass = classPool.get(classFile.name)

            if (ctClass.isFrozen) {
                ctClass.defrost()
            }

            val ctMethod = ctClass.getDeclaredMethod("run")
            val newMethodName = ctMethod.name + "Copy"
            val newMethod = CtNewMethod.copy(ctMethod, newMethodName, ctClass, null)
            ctClass.addMethod(newMethod)
            val sb = StringBuffer()
            sb.append("{try{")
            sb.append(newMethodName)
            sb.append("();}catch(Exception ex){ ex.printStackTrace(); }")
            sb.append("}")
            println("Insert Code:$sb")
            ctMethod.setBody(sb.toString())

            return ctClass
        }
        return null
    }

}