package com.nothing.camera2magic.hook

import android.graphics.ImageFormat
import android.graphics.SurfaceTexture
import android.media.ImageReader
import android.os.Handler
import android.os.HandlerThread
import android.view.Surface
import com.nothing.camera2magic.utils.Dog
import java.util.WeakHashMap

data class BlackHole(
    val identityId: Int,
    val surface: Surface,
    val texture: SurfaceTexture
)
private const val TAG = "[BlackHole]"
object BlackHoleMapper {
    private val oabMap = WeakHashMap<Surface, BlackHole>()
    fun createBlackHole(origin: Surface): Surface {
        return oabMap.getOrPut(origin) {
            val id = 20 + oabMap.size
            val (w, h, f) = NativeBridge.getSurfaceInfo(origin)
            val targetW = if (w > 0) w else 1280
            val targetH = if (h > 0) h else 720
            
            Dog.i(TAG, "Creating proxy SurfaceTexture for $targetW x $targetH", true)
            val texture = SurfaceTexture(0).apply {
                detachFromGLContext()
                setDefaultBufferSize(targetW, targetH)
            }
            val proxySurface = Surface(texture)
            BlackHole(id, proxySurface, texture)
        }.surface
    }

    fun getBlackHole(origin: Surface): Surface? {
        return oabMap[origin]?.surface
    }

    fun clearAll() {
        oabMap.values.forEach {
            it.surface.release()
            it.texture.release()
        }
        oabMap.clear()
    }
}