package com.gh.gamecenter.plugin

import com.gh.gamecenter.plugin.transform.Transformer
import javassist.CtClass
import org.apache.commons.io.IOUtils
import org.gradle.plugins.ide.idea.model.FilePath
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.util.jar.JarOutputStream

class GhTransformHelper {

    private val transformers = ArrayList<Transformer>()

    fun addTransformer(transformer: Transformer) {
        transformers.add(transformer)
    }

    fun proceedModifyDir(filePath: String, inputStream: InputStream) {
        transformers.forEach {
            val ctClass = it.modifyClass(filePath, inputStream)
            ctClass?.let {
                ctClass.writeFile()

                // 释放内存
                ctClass.detach()
            }
        }
        inputStream.close()
    }

    fun proceedModifyJar(filePath: String, jarOutputStream: JarOutputStream, iStream: InputStream) {
        var byteCode: ByteArray? = null
        var inputStream = iStream
        transformers.forEach {
            if (byteCode != null) {
                inputStream = ByteArrayInputStream(byteCode)
            }

            val ctClass = it.modifyClass(filePath, inputStream)
            ctClass?.let {
                byteCode = ctClass.toBytecode()

                // 释放内存
                ctClass.detach()
            }
        }

        if (byteCode == null) {
            byteCode = IOUtils.toByteArray(inputStream)
        }

        jarOutputStream.write(byteCode!!)
        jarOutputStream.flush()
        inputStream.close()
    }

}