package com.narutohuo.xindazhou.core.log

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import com.weijiaxing.logviewer.LogcatActivity

/**
 * 悬浮日志按钮管理器
 * 
 * 提供一个小的悬浮按钮，点击后打开 LogcatViewer 查看日志
 */
@SuppressLint("ClickableViewAccessibility")
object FloatingLogButton {
    
    private const val TAG = "FloatingLogButton"
    
    @Volatile
    private var floatingButton: View? = null
    
    @Volatile
    private var windowManager: WindowManager? = null
    
    @Volatile
    private var isShowing = false
    
    /**
     * 显示悬浮按钮
     */
    fun show(context: Context) {
        if (isShowing || floatingButton != null) {
            Log.d(TAG, "悬浮按钮已显示，跳过")
            return
        }
        
        try {
            val activity = context as? Activity ?: run {
                Log.w(TAG, "context 不是 Activity，无法显示悬浮按钮")
                return
            }
            
            windowManager = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            
            // 创建一个简单的圆形按钮
            floatingButton = ImageView(activity).apply {
                // 使用 Android 系统图标
                setImageResource(android.R.drawable.ic_menu_info_details)
                setBackgroundResource(android.R.drawable.btn_default)
                setPadding(20, 20, 20, 20)
            }
            
            // 设置窗口参数
            val params = WindowManager.LayoutParams().apply {
                width = WindowManager.LayoutParams.WRAP_CONTENT
                height = WindowManager.LayoutParams.WRAP_CONTENT
                type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
                } else {
                    @Suppress("DEPRECATION")
                    WindowManager.LayoutParams.TYPE_PHONE
                }
                flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
                        WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
                format = PixelFormat.TRANSLUCENT
                gravity = Gravity.TOP or Gravity.END
                x = 20
                y = 200
            }
            
            // 添加到窗口
            windowManager?.addView(floatingButton, params)
            isShowing = true
            
            // 点击事件：打开 LogcatViewer
            // 注意：LogcatActivity 已在 AndroidManifest 中设置为 singleTask，确保只有一个实例
            floatingButton?.setOnClickListener {
                Log.d(TAG, "悬浮按钮被点击，打开 LogcatViewer")
                try {
                    LogcatActivity.launch(activity)
                } catch (e: Exception) {
                    Log.e(TAG, "打开 LogcatViewer 失败", e)
                }
            }
            
            // 长按事件：隐藏按钮
            floatingButton?.setOnLongClickListener {
                Log.d(TAG, "悬浮按钮被长按，隐藏按钮")
                hide()
                true
            }
            
            // 支持拖动
            var initialX = 0
            var initialY = 0
            var initialTouchX = 0f
            var initialTouchY = 0f
            
            floatingButton?.setOnTouchListener { v, event ->
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        initialX = params.x
                        initialY = params.y
                        initialTouchX = event.rawX
                        initialTouchY = event.rawY
                        false
                    }
                    MotionEvent.ACTION_MOVE -> {
                        params.x = initialX + (initialTouchX - event.rawX).toInt()
                        params.y = initialY + (event.rawY - initialTouchY).toInt()
                        windowManager?.updateViewLayout(floatingButton, params)
                        true
                    }
                    else -> false
                }
            }
            
            Log.d(TAG, "悬浮按钮显示成功")
            
        } catch (e: Exception) {
            Log.e(TAG, "显示悬浮按钮失败", e)
            isShowing = false
            floatingButton = null
        }
    }
    
    /**
     * 隐藏悬浮按钮
     */
    fun hide() {
        try {
            floatingButton?.let {
                windowManager?.removeView(it)
                floatingButton = null
                isShowing = false
                Log.d(TAG, "悬浮按钮已隐藏")
            }
        } catch (e: Exception) {
            Log.e(TAG, "隐藏悬浮按钮失败", e)
        }
    }
    
    /**
     * 切换显示/隐藏
     */
    fun toggle(context: Context) {
        if (isShowing) {
            hide()
        } else {
            show(context)
        }
    }
}

