package com.example.myapplication.keyboard

import android.content.res.ColorStateList
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView

/**
 * 所有键盘的基础类：只处理文本颜色、边距 / 内边距 这些通用样式。
 * 不再直接访问 resources，统一走 env.ctx.resources。
 */
abstract class BaseKeyboard(
    protected val env: KeyboardEnvironment
) {
    abstract val rootView: View

    /**
     * 应用主题：文字颜色 + 边框（只调 margin/padding，不动你每个键的图片背景）
     */
    open fun applyTheme(
        textColor: ColorStateList,
        borderColor: ColorStateList,
        backgroundColor: ColorStateList
    ) {
        applyTextColorToAllTextViews(rootView, textColor)
        applyBorderToAllKeyViews(rootView)
    }

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

        fun dfs(v: View?) {
            when (v) {
                is TextView -> v.setTextColor(color)
                is ViewGroup -> {
                    val childCount = v.childCount
                    var i = 0
                    while (i < childCount) {
                        dfs(v.getChildAt(i))
                        i++
                    }
                }
            }
        }

        dfs(root)
    }

    /**
     * 只设置 margin / padding，不统一改背景，避免覆盖你用 ThemeManager 设置的按键图。
     * 跟你原来 MyInputMethodService.applyBorderColorToAllKeys 的逻辑保持一致。
     */
    protected fun applyBorderToAllKeyViews(root: View?) {
        if (root == null) return

        val res = env.ctx.resources
        val pkg = env.ctx.packageName

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

        // 忽略 suggestion_0..20（联想栏），不改它们背景
        val ignoredIds = HashSet<Int>().apply {
            var i = 0
            while (i <= 20) {
                val id = res.getIdentifier("suggestion_$i", "id", pkg)
                if (id != 0) add(id)
                i++
            }
        }

        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 -> {
                    val childCount = v.childCount
                    var i = 0
                    while (i < childCount) {
                        dfs(v.getChildAt(i))
                        i++
                    }
                }
            }
        }

        dfs(root)
    }

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