package com.example.defenseapplication.view

import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.camera.core.ExperimentalGetImage
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.face.FaceDetector
/*
* 人脸分析器
* */
@ExperimentalGetImage
class FaceAnalyzer(
    private val detector: FaceDetector?,
    private val overlayView: FaceOverlayView
) : ImageAnalysis.Analyzer {

    override fun analyze(imageProxy: ImageProxy) {
        if (detector == null) {
            imageProxy.close()
            return
        }
        val mediaImage = imageProxy.image ?: run {
            imageProxy.close()
            return
        }
        val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)

        detector.process(image)
            .addOnSuccessListener { faces ->
                Handler(Looper.getMainLooper()).post {
                    overlayView.setFaces(faces)
                }
            }
            .addOnFailureListener { e ->
                Log.e("FaceAnalyzer", "人脸检测失败", e)
            }
            .addOnCompleteListener {
                imageProxy.close()
            }
    }
}