package com.humand.demo.modules.FaceDetectionConfirmation

import android.net.Uri
import android.util.Log
import com.facebook.react.bridge.ReactApplicationContext
import com.google.android.gms.tasks.Tasks
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.face.FaceDetection
import com.google.mlkit.vision.face.FaceDetector
import com.google.mlkit.vision.face.FaceDetectorOptions

private const val TAG = "FaceDetector"

class FaceDetectionConfirmationModule(private val reactContext: ReactApplicationContext) {
    private var faceDetector: FaceDetector? = null

    init {
        val performanceModeValue = FaceDetectorOptions.PERFORMANCE_MODE_FAST
        val landmarkModeValue = FaceDetectorOptions.LANDMARK_MODE_NONE
        val classificationModeValue = FaceDetectorOptions.CLASSIFICATION_MODE_NONE
        val contourModeValue = FaceDetectorOptions.CONTOUR_MODE_NONE

        val optionsBuilder = FaceDetectorOptions.Builder()
            .setPerformanceMode(performanceModeValue)
            .setLandmarkMode(landmarkModeValue)
            .setContourMode(contourModeValue)
            .setClassificationMode(classificationModeValue)


        faceDetector = FaceDetection.getClient(
            optionsBuilder.build()
        )
    }

    fun hasFace(path: String): Boolean {
        try {
            val image = InputImage.fromFilePath(reactContext, Uri.parse(path))
            val task = faceDetector!!.process(image)
            val faces = Tasks.await(task)
            return faces.size > 0
        } catch (e: Exception) {
            Log.e(TAG, "Error processing face detection: ", e)
            return false
        }
    }
}
