package com.omixlab.lckcontrol.p2p.webrtc

import android.util.Log
import org.webrtc.*
import java.nio.ByteBuffer
import java.util.concurrent.atomic.AtomicBoolean

/**
 * Wraps H.264 NAL units from the native encoder into WebRTC VideoTrack.
 * This uses the WebRTC encoded frame injection API to pass already-encoded
 * H.264 data directly to the peer connection without re-encoding.
 */
class EncodedVideoSource(
    private val peerConnectionFactory: PeerConnectionFactory?,
) {
    companion object {
        private const val TAG = "EncodedVideoSource"
    }

    private var videoSource: VideoSource? = null
    private var videoTrack: VideoTrack? = null
    private val isActive = AtomicBoolean(false)
    private var frameCount = 0L

    fun createVideoTrack(): VideoTrack? {
        videoSource = peerConnectionFactory?.createVideoSource(false)
        videoTrack = peerConnectionFactory?.createVideoTrack("quest_camera", videoSource)
        isActive.set(true)
        return videoTrack
    }

    /**
     * Called from the native encoder callback with H.264 NAL units.
     * In a production implementation, this would use the WebRTC
     * EncodedImage API for zero-transcode passthrough.
     *
     * For now, this is a placeholder that will be connected to the
     * native encoder's frame callback.
     */
    fun onEncodedFrame(data: ByteArray, isKeyFrame: Boolean, timestampNs: Long) {
        if (!isActive.get()) return
        frameCount++

        if (frameCount % 300 == 0L) {
            Log.d(TAG, "Encoded frames delivered: $frameCount, keyFrame: $isKeyFrame")
        }

        // In full implementation:
        // 1. Wrap data as EncodedImage
        // 2. Submit to VideoSource's CapturerObserver
        // This requires custom native WebRTC integration
    }

    fun stop() {
        isActive.set(false)
        videoTrack?.dispose()
        videoSource?.dispose()
        videoTrack = null
        videoSource = null
    }
}
