package com.example.defenseapplication.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import com.google.mlkit.vision.face.Face

class FaceOverlayView(context: Context, attrs: AttributeSet?) : View(context, attrs) {
    private val framePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.WHITE
        style = Paint.Style.STROKE
        strokeWidth = 6f
    }
    private val maskPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.parseColor("#7A000000")
        style = Paint.Style.FILL
    }

    private val facePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.parseColor("#80FFFFFF")
        style = Paint.Style.STROKE
        strokeWidth = 3f
    }

    private val maskPath = Path()
    private val frameRect = RectF()
    private var faces = mutableListOf<Face>()

    fun setFaces(faces: List<Face>) {
        this.faces = faces.toMutableList()
        invalidate()  // 触发 onDraw
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val cx = width / 2f
        val cy = height * 0.45f
        val radius = minOf(width, height) * 0.31f

        maskPath.reset()
        maskPath.addRect(0f, 0f, width.toFloat(), height.toFloat(), Path.Direction.CW)
        maskPath.addCircle(cx, cy, radius, Path.Direction.CCW)
        canvas.drawPath(maskPath, maskPaint)
        canvas.drawCircle(cx, cy, radius, framePaint)

        frameRect.set(cx - radius, cy - radius, cx + radius, cy + radius)
        for (face in faces) {
            val rect = face.boundingBox
            val clippedLeft = rect.left.coerceAtLeast(frameRect.left.toInt()).toFloat()
            val clippedTop = rect.top.coerceAtLeast(frameRect.top.toInt()).toFloat()
            val clippedRight = rect.right.coerceAtMost(frameRect.right.toInt()).toFloat()
            val clippedBottom = rect.bottom.coerceAtMost(frameRect.bottom.toInt()).toFloat()
            if (clippedRight > clippedLeft && clippedBottom > clippedTop) {
                canvas.drawRect(clippedLeft, clippedTop, clippedRight, clippedBottom, facePaint)
            }
        }
    }
}