package com.assimilate.alltrans.curview

import android.content.Context
import android.graphics.*
import android.media.ImageReader
import android.os.Build
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.Toast
import com.assimilate.alltrans.R
import com.assimilate.alltrans.databinding.LayoutSusSelectBinding

class SelectionView(private val context: Context) {
    private lateinit var binding: LayoutSusSelectBinding
    private lateinit var selectionView: View
    private lateinit var overlayView: FrameLayout
    private val windowManager: WindowManager =
        context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    private var startX = 0
    private var startY = 0
    private var endX = 0
    private var endY = 0

    fun addSelectionView(imageReader: ImageReader) {
        binding = LayoutSusSelectBinding.inflate(LayoutInflater.from(context))
        overlayView = FrameLayout(context).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        }

        overlayView.addView(binding.root)
        selectionView = SelectionRectView(context)
        overlayView.addView(selectionView)

        val overlayParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            },
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS or
                    WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR,
            PixelFormat.TRANSLUCENT
        )

        windowManager.addView(overlayView, overlayParams)
        Toast.makeText(context, context.getString(R.string.select_toast), Toast.LENGTH_SHORT).show()


        overlayView.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    startX = event.rawX.toInt()
                    startY = event.rawY.toInt()
                    true
                }

                MotionEvent.ACTION_MOVE -> {
                    endX = event.rawX.toInt()
                    endY = event.rawY.toInt()
                    updateSelectionRect()
                    true
                }

                MotionEvent.ACTION_UP -> {
                    endX = event.rawX.toInt()
                    endY = event.rawY.toInt()
                    Log.d("SelectionView", "Selected area: ($startX, $startY) to ($endX, $endY)")
                    removeSelectionView()
                    // 确保坐标顺序正确
                    val left = Math.min(startX, endX)
                    val top = Math.min(startY, endY)
                    val right = Math.max(startX, endX)
                    val bottom = Math.max(startY, endY)
                    Log.d(
                        "SelectionView",
                        "Corrected selected area: ($left, $top) to ($right, $bottom)"
                    )
                    // 调用 DistrictView 的方法
                    val districtView = DistrictView(context)
                    districtView.showDistrictView(imageReader, left, top, right, bottom)
                    true
                }

                else -> false
            }
        }

        binding.susGlobalClose.setOnClickListener {
            removeSelectionView()
        }
    }

    private fun updateSelectionRect() {
        val left = Math.min(startX, endX)
        val top = Math.min(startY, endY)
        val right = Math.max(startX, endX)
        val bottom = Math.max(startY, endY)
        (selectionView as SelectionRectView).updateRect(Rect(left, top, right, bottom))
    }

    fun removeSelectionView() {
        windowManager.removeView(overlayView)
    }

    inner class SelectionRectView(context: Context) : View(context) {
        private val paint = Paint().apply {
            color = Color.WHITE
            style = Paint.Style.FILL
            alpha = 128
        }
        private var rect: Rect? = null

        override fun onDraw(canvas: Canvas) {
            super.onDraw(canvas)
            rect?.let {
                canvas.drawRect(it, paint)

            }
        }

        fun updateRect(rect: Rect) {
            this.rect = rect
            invalidate()
        }
    }


}
