package com.assimilate.alltrans.curview

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.view.MotionEvent
import android.view.View
import com.assimilate.alltrans.listeners.OnRegionSelectedListener

class DrawChooseView(context: Context) : View(context) {
    private var paintTransparent: Paint = Paint()
    private var paintSemiTransparent: Paint = Paint()
    private var rect: Rect? = null

    private var startX: Float = 0f
    private var startY: Float = 0f

    init {
        paintTransparent.color = Color.TRANSPARENT
        paintTransparent.style = Paint.Style.FILL

        paintSemiTransparent.color = Color.parseColor("#88000000")  // 半透明黑色
        paintSemiTransparent.style = Paint.Style.FILL
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        rect?.let {
            val left = Math.min(it.left, it.right)
            val right = Math.max(it.left, it.right)
            val top = Math.min(it.top, it.bottom)
            val bottom = Math.max(it.top, it.bottom)

            // 绘制框选外的半透明区域
            canvas.drawRect(0f, 0f, width.toFloat(), top.toFloat(), paintSemiTransparent)
            canvas.drawRect(0f, top.toFloat(), left.toFloat(), bottom.toFloat(), paintSemiTransparent)
            canvas.drawRect(right.toFloat(), top.toFloat(), width.toFloat(), bottom.toFloat(), paintSemiTransparent)
            canvas.drawRect(0f, bottom.toFloat(), width.toFloat(), height.toFloat(), paintSemiTransparent)

            // 绘制框选内的透明区域
            canvas.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), paintTransparent)
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                startX = event.x
                startY = event.y
                rect = Rect(startX.toInt(), startY.toInt(), startX.toInt(), startY.toInt())
                invalidate()
                return true
            }

            MotionEvent.ACTION_MOVE -> {
                rect?.apply {
                    right = event.x.toInt()
                    bottom = event.y.toInt()
                }
                invalidate()
                return true
            }

            MotionEvent.ACTION_UP -> {
                rect?.let {
                    (context as? OnRegionSelectedListener)?.onRegionSelected(it)
                }
                return true
            }
        }
        return super.onTouchEvent(event)
    }
}
