package com.gh.gamecenter.plugin.transform

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

class ExoSourceManagerTransformer : Transformer {

    private val classPool = ClassPool.getDefault()

    override fun getModifyClassName(): String {
        return "ExoSourceManager.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 method = ctClass.getDeclaredMethod("release")
            //必须使用全类名，否则编译会找不到类
            val body = "int size = com.gh.gamecenter.video.detail.CustomManager.getVideoManagerSize();" +
                    "if (size > 0) { android.util.Log.e(\"gh_tag\",\"release：拦截成功\");" +
                    "return;}"
            method.insertBefore(body)
            println("Insert Code:" + method.name + "\n" + body)
            return ctClass
        }
        return null
    }

}