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 AppCompatEditTextTransformer : Transformer {

    private val classPool = ClassPool.getDefault()

    override fun getModifyClassName(): String {
        return "AppCompatEditText"
    }

    override fun modifyClass(filePath: String, inputStream: InputStream): CtClass? {
        if (filePath.contains(getModifyClassName())) {

            System.out.println("发现 AppCompatEditText")

            val classFile = ClassFile(DataInputStream(BufferedInputStream(inputStream)))
            val ctClass = classPool.get(classFile.name)

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

            // 使用 try catch 包裹找到的第一个 onTextContextMenuItem 方法 （若能找到的话）
            // https://sentry.shanqu.cc/organizations/lightgame/issues/277509
            try {
                val ctMethod = ctClass.getDeclaredMethod("onTextContextMenuItem")

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

                System.out.println("为 AppCompatEditText.onTextContextMenuItem 添加 try catch")
            } catch (e: NotFoundException) {
                e.printStackTrace()
            }

            return ctClass
        }
        return null
    }

}