package ai.guiji.duix.sample.plugin.facedetect;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;

import com.google.mediapipe.solutions.facedetection.FaceDetection;
import com.google.mediapipe.solutions.facedetection.FaceDetectionOptions;

public class MediaPipeFaceDetect {

    public final String TAG = getClass().getName();

    FaceDetection faceDetection;
    MediaPipeFaceDetectCallback callback;

    Bitmap currentBitmap;

    public MediaPipeFaceDetect(Context context, MediaPipeFaceDetectCallback callback) {
        this.callback = callback;
        faceDetection = new FaceDetection(context, FaceDetectionOptions.builder()
                .setStaticImageMode(true)
                .setModelSelection(0)
                .setMinDetectionConfidence(0.5f)
                .build());
        faceDetection.setResultListener(result -> {
            Log.e(TAG, "FaceDetectionResult:" + result.toString());
            int size = result.multiFaceDetections().size();
            if (callback != null) {
                callback.onMediaPipeFaceDetect(size);
            }
        });
        faceDetection.setErrorListener((message, e) -> Log.e(TAG, "MediaPipe Face Detection error:" + message));
    }

    public void faceDetect(Bitmap bitmap) {
        if (currentBitmap != null) {
            currentBitmap.recycle();
        }
        currentBitmap = bitmap;
        faceDetection.send(currentBitmap);
    }

    public void release(){
        if (currentBitmap != null) {
            currentBitmap.recycle();
        }
    }

    public interface MediaPipeFaceDetectCallback {
        void onMediaPipeFaceDetect(int faceCount);
    }
}
