package com.example.myapplication.keyboard

import android.content.Context
import android.content.res.ColorStateList
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView

abstract class BaseKeyboard(
    protected val env: KeyboardEnvironment
) {
    protected val vibrator: Vibrator? = env.ctx.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator
    /** 根布局 */
    abstract val rootView: View

    /**
     * 应用主题：文字颜色 + 边框 + 按键背景
     * 调用后文字颜色、边框立即生效，子类刷新按键背景
     */
    open fun applyTheme(
        textColor: ColorStateList,
        borderColor: ColorStateList,
        backgroundColor: ColorStateList
    ) {
        // 文字颜色递归设置
        applyTextColorToAllTextViews(rootView, textColor)

        // 边框（margin / padding）递归设置
        applyBorderToAllKeyViews(rootView)

        // 子类刷新按键背景（如 ThemeManager 提供的图片）
        applyKeyBackgroundsForTheme()
    }

    /** 子类实现：刷新按键背景 */
    abstract fun applyKeyBackgroundsForTheme()

    // ------------------- 工具方法 -------------------

    /** 递归设置 TextView 文字颜色 */
    protected fun applyTextColorToAllTextViews(root: View?, color: ColorStateList) {
        if (root == null) return

        fun dfs(v: View?) {
            when (v) {
                is TextView -> v.setTextColor(color)
                is ViewGroup -> {
                    for (i in 0 until v.childCount) {
                        dfs(v.getChildAt(i))
                    }
                }
            }
        }

        dfs(root)
    }

    /**
     * 只设置 margin / padding，不改背景，避免覆盖 ThemeManager 设置的按键图
     */
    protected fun applyBorderToAllKeyViews(root: View?) {
        if (root == null) return

        val keyMarginPx = 1.dpToPx()
        val keyPaddingH = 6.dpToPx()

        // 忽略 suggestion_0..20（联想栏）
        val ignoredIds = HashSet<Int>().apply {
            val res = env.ctx.resources
            val pkg = env.ctx.packageName
            for (i in 0..20) {
                val id = res.getIdentifier("suggestion_$i", "id", pkg)
                if (id != 0) add(id)
            }
        }

        fun dfs(v: View?) {
            when (v) {
                is TextView -> {
                    if (ignoredIds.contains(v.id)) return

                    val lp = v.layoutParams
                    if (lp is LinearLayout.LayoutParams) {
                        lp.setMargins(keyMarginPx, keyMarginPx, keyMarginPx, keyMarginPx)
                        v.layoutParams = lp
                    }
                    v.setPadding(
                        keyPaddingH,
                        v.paddingTop,
                        keyPaddingH,
                        v.paddingBottom
                    )
                }
                is ViewGroup -> {
                    for (i in 0 until v.childCount) {
                        dfs(v.getChildAt(i))
                    }
                }
            }
        }

        dfs(root)
    }

    /** dp -> px */
    protected fun Int.dpToPx(): Int {
        val density = env.ctx.resources.displayMetrics.density
        return (this * density + 0.5f).toInt()
    }

    /** 按键震动 */
    protected fun vibrateKey() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            vibrator?.vibrate(VibrationEffect.createOneShot(20, VibrationEffect.DEFAULT_AMPLITUDE))
        } else {
            @Suppress("DEPRECATION")
            vibrator?.vibrate(20)
        }
    }
}
