package com.atmob.keyboard_android.floating

import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import android.os.IBinder
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import com.atmob.keyboard_android.R
import com.atmob.keyboard_android.ext.click
import com.atmob.keyboard_android.keyboard.InputMethodPickerActivity
import com.atmob.keyboard_android.util.flow.FloatingWindowUtil
import kotlin.math.abs

/**
 * 悬浮窗按钮服务
 */
class FloatingButtonService : Service() {
    private lateinit var windowManager: WindowManager
    private lateinit var floatingView: View
    private lateinit var layoutParams: WindowManager.LayoutParams

    companion object {
        /**
         * 启动服务
         */
        fun start(context: Context) {
            // 检查是否有悬浮窗权限，没有则跳转到设置页面
            if (!FloatingWindowUtil.hasFloatingWindowPermission(context)) {
                FloatingWindowUtil.tryJumpToPermissionPage(context)
            } else {
                // 有权限，开启悬浮窗
                val serviceIntent = Intent(context, FloatingButtonService::class.java)
                context.startService(serviceIntent)
            }
        }

        /**
         * 停止服务
         */
        fun stop(context: Context) {
            val serviceIntent = Intent(context, FloatingButtonService::class.java)
            context.stopService(serviceIntent)
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate() {
        super.onCreate()
        // 初始化 WindowManager
        windowManager = getSystemService(WINDOW_SERVICE) as WindowManager

        // 加载悬浮窗布局
        floatingView =
            LayoutInflater.from(this).inflate(R.layout.floating_button_layout, null, false)

        // 悬浮窗参数
        layoutParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            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_NOT_TOUCH_MODAL or
                    WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
            PixelFormat.TRANSLUCENT
        )
        layoutParams.gravity = Gravity.TOP or Gravity.START

        val screenWidth = resources.displayMetrics.widthPixels
        val screenHeight = resources.displayMetrics.heightPixels
        // 初始位置在屏幕右侧
        layoutParams.x = screenWidth
        // 初始位置在屏幕中间
        layoutParams.y = screenHeight / 2

        // 拖动逻辑（带吸附效果）
        val floatingButton = floatingView.findViewById<ImageView>(R.id.floating_button)
        floatingButton.setOnTouchListener(object : View.OnTouchListener {
            private var initialX = 0
            private var initialY = 0
            private var touchX = 0f
            private var touchY = 0f
            private var isClick = false

            override fun onTouch(v: View, event: MotionEvent): Boolean {
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        initialX = layoutParams.x
                        initialY = layoutParams.y
                        touchX = event.rawX
                        touchY = event.rawY
                        // 认为是点击事件，后续会判断是否有拖动
                        isClick = true
                        return false
                    }

                    MotionEvent.ACTION_MOVE -> {
                        val deltaX = (event.rawX - touchX).toInt()
                        val deltaY = (event.rawY - touchY).toInt()
                        if (abs(deltaX) > 10 || abs(deltaY) > 10) {
                            // 发生拖动，不是点击
                            isClick = false
                        }
                        layoutParams.x = initialX + deltaX
                        layoutParams.y = initialY + deltaY
                        windowManager.updateViewLayout(floatingView, layoutParams)
                        return true
                    }

                    MotionEvent.ACTION_UP -> {
                        if (isClick) {
                            // 触发点击事件
                            v.performClick()
                        } else {
                            snapToEdge()
                        }
                        return true
                    }
                }
                return false
            }
        })

        // 点击按钮，弹出输入法选择框
        floatingButton.click {
            InputMethodPickerActivity.start(this)
        }

        // 添加悬浮窗到屏幕
        windowManager.addView(floatingView, layoutParams)
    }

    /**
     * 吸附到最近的屏幕边缘
     */
    private fun snapToEdge() {
        val screenWidth = resources.displayMetrics.widthPixels
        val middle = screenWidth / 2f
        layoutParams.x = if (layoutParams.x < middle) {
            // 屏幕左边
            0
        } else {
            // 屏幕右边
            screenWidth - floatingView.width
        }
        windowManager.updateViewLayout(floatingView, layoutParams)
    }

    override fun onDestroy() {
        super.onDestroy()
        windowManager.removeView(floatingView)
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
}