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

    private val classPool = ClassPool.getDefault()

    override fun getModifyClassName(): String {
        return "DiskLruCache.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 {
                val method = ctClass.getDeclaredMethod("trimToSize")
                val body = "if(!lruEntries.values().iterator().hasNext()) {" +
                        "android.util.Log.e(\"gh_tag\",\"trimToSize：拦截成功\");" +
                        "mostRecentTrimFailed = false;" +
                        "return;" +
                        "}"
                method.insertAt(684, body)
                println("Insert Code:" + method.name + "\n" + body)
            } catch (e: Exception) {
                e.printStackTrace()
            }

            return ctClass
        }
        return null
    }

}