package com.gh.gamecenter.plugin.transform

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

class ActivityTransformer : Transformer {

    private val classPool = ClassPool.getDefault()

    override fun getModifyClassName(): String {
        return "ComponentActivity.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()
            }

            // 使用 try catch 包裹找到的第一个 startActivityForResult 方法 （若能找到的话）
            // https://sentry.shanqu.cc/organizations/lightgame/issues/221480/?project=22&query=level%3Afatal+is%3Aunresolved&sort=freq&statsPeriod=14d
            try {
                val ctMethod = ctClass.getDeclaredMethod("startActivityForResult")

                val exceptionType: CtClass = ClassPool.getDefault().get("java.lang.Exception")
                val catchBody = "{ System.out.println(\$e); return null; }"
                ctMethod.addCatch(catchBody, exceptionType)
            } catch (e: NotFoundException) {
                e.printStackTrace()
            }

            return ctClass
        }
        return null
    }

}