package com.hikoncont.manager

import android.accessibilityservice.GestureDescription
import android.graphics.Path
import android.graphics.PointF
import android.util.Log
import com.hikoncont.service.AccessibilityRemoteService
import kotlinx.coroutines.*

/**
 * 手势控制器
 * 
 * 负责处理各种手势操作：
 * 1. 基础点击操作
 * 2. 滑动手势
 * 3. 长按操作
 * 4. 多点触控
 */
class GestureController(private val service: AccessibilityRemoteService) {
    
    companion object {
        private const val TAG = "GestureController"
        private const val CLICK_DURATION = 50L
        private const val LONG_PRESS_DURATION = 1000L
        private const val SWIPE_DURATION = 300L
    }
    
    private val gestureScope = CoroutineScope(Dispatchers.Main)
    
    /**
     * 执行手势操作（覆盖窗口不影响系统级手势操作）
     */
    private fun executeGesture(gestureAction: () -> Unit) {
        try {
            // 直接执行手势操作，不需要管理覆盖窗口
            gestureAction()
        } catch (e: Exception) {
            Log.e(TAG, "执行手势操作失败", e)
        }
    }
    
    /**
     * 执行点击操作
     */
    fun performClick(x: Float, y: Float) {
        executeGesture {
            val path = Path().apply { moveTo(x, y) }
            val stroke = GestureDescription.StrokeDescription(path, 0, CLICK_DURATION)
            val gesture = GestureDescription.Builder().addStroke(stroke).build()
            
            service.dispatchGesture(gesture, null, null)
            Log.d(TAG, "执行点击操作: ($x, $y)")
        }
    }
    
    /**
     * 执行长按操作
     */
    fun performLongPress(x: Float, y: Float) {
        executeGesture {
            val path = Path().apply { moveTo(x, y) }
            val stroke = GestureDescription.StrokeDescription(path, 0, LONG_PRESS_DURATION)
            val gesture = GestureDescription.Builder().addStroke(stroke).build()
            
            service.dispatchGesture(gesture, null, null)
            Log.d(TAG, "执行长按操作: ($x, $y)")
        }
    }
    
    /**
     * 执行滑动操作
     */
    fun performSwipe(startX: Float, startY: Float, endX: Float, endY: Float, duration: Long = SWIPE_DURATION) {
        executeGesture {
            val path = Path().apply {
                moveTo(startX, startY)
                lineTo(endX, endY)
            }
            
            val stroke = GestureDescription.StrokeDescription(path, 0, duration)
            val gesture = GestureDescription.Builder().addStroke(stroke).build()
            
            service.dispatchGesture(gesture, null, null)
            Log.d(TAG, "执行滑动操作: ($startX, $startY) -> ($endX, $endY)")
        }
    }
    
    /**
     * 执行双指缩放手势
     */
    fun performPinchGesture(centerX: Float, centerY: Float, startDistance: Float, endDistance: Float, duration: Long = 500) {
        executeGesture {
            val angle1 = 0f
            val angle2 = Math.PI.toFloat()
            
            // 第一个手指的路径
            val startX1 = centerX + (startDistance / 2) * kotlin.math.cos(angle1)
            val startY1 = centerY + (startDistance / 2) * kotlin.math.sin(angle1)
            val endX1 = centerX + (endDistance / 2) * kotlin.math.cos(angle1)
            val endY1 = centerY + (endDistance / 2) * kotlin.math.sin(angle1)
            
            val path1 = Path().apply {
                moveTo(startX1, startY1)
                lineTo(endX1, endY1)
            }
            
            // 第二个手指的路径
            val startX2 = centerX + (startDistance / 2) * kotlin.math.cos(angle2)
            val startY2 = centerY + (startDistance / 2) * kotlin.math.sin(angle2)
            val endX2 = centerX + (endDistance / 2) * kotlin.math.cos(angle2)
            val endY2 = centerY + (endDistance / 2) * kotlin.math.sin(angle2)
            
            val path2 = Path().apply {
                moveTo(startX2, startY2)
                lineTo(endX2, endY2)
            }
            
            val stroke1 = GestureDescription.StrokeDescription(path1, 0, duration)
            val stroke2 = GestureDescription.StrokeDescription(path2, 0, duration)
            
            val gesture = GestureDescription.Builder()
                .addStroke(stroke1)
                .addStroke(stroke2)
                .build()
            
            service.dispatchGesture(gesture, null, null)
            Log.d(TAG, "执行缩放手势: center($centerX, $centerY), distance: $startDistance -> $endDistance")
        }
    }
    
    /**
     * 执行多点触控
     */
    fun performMultiTouch(points: List<PointF>, duration: Long = 300) {
        executeGesture {
            val gestureBuilder = GestureDescription.Builder()
            
            points.forEachIndexed { index, point ->
                val path = Path().apply { moveTo(point.x, point.y) }
                val stroke = GestureDescription.StrokeDescription(path, 0, duration)
                gestureBuilder.addStroke(stroke)
            }
            
            val gesture = gestureBuilder.build()
            service.dispatchGesture(gesture, null, null)
            Log.d(TAG, "执行多点触控: ${points.size}个触点")
        }
    }
    

    
    /**
     * 🔧 执行连续长按拖拽操作（优化版本）
     * 
     * @param pathPoints 拖拽路径上的所有点
     * @param duration 拖拽总时长
     */
    fun performContinuousLongPressDrag(pathPoints: List<PointF>, duration: Long = 1500L) {
        if (pathPoints.isEmpty()) {
            Log.w(TAG, "路径点为空，无法执行长按拖拽")
            return
        }
        
        executeGesture {
            val startPoint = pathPoints[0]
            val endPoint = pathPoints.last()
            
            if (pathPoints.size == 1) {
                // 只有一个点，执行普通长按
                val path = Path().apply { moveTo(startPoint.x, startPoint.y) }
                val stroke = GestureDescription.StrokeDescription(path, 0, LONG_PRESS_DURATION)
                val gesture = GestureDescription.Builder().addStroke(stroke).build()
                service.dispatchGesture(gesture, null, null)
                Log.d(TAG, "执行长按操作: (${startPoint.x}, ${startPoint.y})")
            } else {
                // 单一连续手势避免系统手势冲突
                val totalDuration = maxOf(LONG_PRESS_DURATION + 500L, duration)
                
                // 🔧 核心技巧：在起始点重复添加相同坐标来延长停留时间
                val path = Path().apply {
                    moveTo(startPoint.x, startPoint.y)
                    
                    // 关键：在起始点重复添加相同坐标（不是微移动）
                    // 这样系统会在同一点停留更长时间，触发长按
                    repeat(50) {  // 增加重复次数确保长按触发
                        lineTo(startPoint.x, startPoint.y)
                    }
                    
                    // 然后移动到路径上的各个点
                    for (i in 1 until pathPoints.size) {
                        val point = pathPoints[i]
                        lineTo(point.x, point.y)
                    }
                }
                
                // 单一连续stroke，避免手势断开
                val stroke = GestureDescription.StrokeDescription(path, 0, totalDuration)
                val gesture = GestureDescription.Builder().addStroke(stroke).build()
                
                service.dispatchGesture(gesture, null, null)
                Log.d(TAG, "执行长按拖拽: 起点(${startPoint.x}, ${startPoint.y}) -> 终点(${endPoint.x}, ${endPoint.y}), 路径点数=${pathPoints.size}, 总时长=${totalDuration}ms (单一连续手势)")
            }
        }
    }
    


    /**
     * 执行连续手势序列
     */
    fun performGestureSequence(gestures: List<GestureCommand>) {
        gestureScope.launch {
            for (gesture in gestures) {
                when (gesture.type) {
                    GestureType.CLICK -> performClick(gesture.x, gesture.y)
                    GestureType.LONG_PRESS -> performLongPress(gesture.x, gesture.y)
                    GestureType.SWIPE -> performSwipe(gesture.startX, gesture.startY, gesture.endX, gesture.endY, gesture.duration)
                    GestureType.PINCH -> performPinchGesture(gesture.centerX, gesture.centerY, gesture.startDistance, gesture.endDistance, gesture.duration)
                    GestureType.MULTI_TOUCH -> {
                        // 处理多点触控
                        val points = listOf(PointF(gesture.x, gesture.y))
                        performMultiTouch(points, gesture.duration)
                    }

                }
                
                // 等待手势完成再执行下一个
                delay(gesture.interval)
            }
        }
    }
    
    /**
     * 清理资源
     */
    fun release() {
        gestureScope.cancel()
    }
}

/**
 * 手势类型
 */
enum class GestureType {
    CLICK,
    LONG_PRESS,
    SWIPE,
    PINCH,
    MULTI_TOUCH
}

/**
 * 手势命令
 */
data class GestureCommand(
    val type: GestureType,
    val x: Float = 0f,
    val y: Float = 0f,
    val startX: Float = 0f,
    val startY: Float = 0f,
    val endX: Float = 0f,
    val endY: Float = 0f,
    val centerX: Float = 0f,
    val centerY: Float = 0f,
    val startDistance: Float = 0f,
    val endDistance: Float = 0f,
    val duration: Long = 300L,
    val interval: Long = 100L
) 