package com.example.myapplication

import android.content.ComponentName
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplication.MyInputMethodService


class ImeGuideActivity : AppCompatActivity() {

    private lateinit var btnEnable: LinearLayout
    private lateinit var btnSelect: LinearLayout
    private lateinit var tvStep1Status: TextView//
    private lateinit var tvStep2Status: TextView//
    private lateinit var btnEnabledText: TextView//
    private lateinit var btnSelectText: TextView//
    private lateinit var btnEnabledimg: ImageView//
    private lateinit var btnSelectimg: ImageView//

    private var imeObserver: android.database.ContentObserver? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ime_guide)

        // // 设置关闭按钮点击事件
        // findViewById<FrameLayout>(R.id.iv_close).setOnClickListener {
        //     finish()
        // }

        btnEnable = findViewById(R.id.enabled)//btn启用输入法
        btnSelect = findViewById(R.id.select)//btn选择输入法
        tvStep1Status = findViewById(R.id.Steps)//第一步的提示
        tvStep2Status = findViewById(R.id.stepTips)//第二步的提示
        btnEnabledText = findViewById(R.id.btnEnabledText)//启用输入法按钮文字
        btnSelectText = findViewById(R.id.btnSelectText)//选择输入法按钮文字
        btnEnabledimg = findViewById(R.id.btnEnabledimg)//启用输入法按钮图片
        btnSelectimg = findViewById(R.id.btnSelectimg)//选择输入法按钮图片

        // // 第一步：启用输入法
        // btnEnable.setOnClickListener {
        //     startActivity(Intent(Settings.ACTION_INPUT_METHOD_SETTINGS))
        // }
        

        // // 第二步：切换输入法
        // btnSelect.setOnClickListener {
        //     val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        //     imm.showInputMethodPicker()
        // }
    }

    override fun onResume() {
        super.onResume()
        refreshStatus()
        registerImeObserver()
    }

    override fun onPause() {
        super.onPause()
        unregisterImeObserver()
    }

    private fun registerImeObserver() {
        if (imeObserver != null) return
    
        imeObserver = object : android.database.ContentObserver(
            android.os.Handler(android.os.Looper.getMainLooper())
        ) {
            override fun onChange(selfChange: Boolean) {
                super.onChange(selfChange)
                refreshStatus()
            }
        }
    
        contentResolver.registerContentObserver(
            android.provider.Settings.Secure.getUriFor(
                android.provider.Settings.Secure.DEFAULT_INPUT_METHOD
            ),
            false,
            imeObserver!!
        )
    }
    
    private fun unregisterImeObserver() {
        imeObserver?.let {
            contentResolver.unregisterContentObserver(it)
        }
        imeObserver = null
    }

    /** 刷新步骤状态（是否启用/选择） */
    private fun refreshStatus() {
        val enabled = isImeEnabled()
        val selected = isImeSelected()
        
        // 根据状态设置按钮的点击行为
        if (enabled) {
            // 输入法已启用时，禁用启用按钮的点击事件
            btnEnable.setOnClickListener(null)
        } else {
            // 输入法未启用时，设置启用按钮的点击事件
            btnEnable.setOnClickListener {
                startActivity(Intent(Settings.ACTION_INPUT_METHOD_SETTINGS))
            }
        }

        if (selected) {
            // 输入法已切换时，禁用选择按钮的点击事件
            btnSelect.setOnClickListener(null)
        } else {
            // 输入法未切换时，设置选择按钮的点击事件
            btnSelect.setOnClickListener {
                val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                imm.showInputMethodPicker()
            }
        }

        if(!enabled &&!selected) {
            btnEnable.background = getDrawable(R.drawable.ime_guide_activity_btn_unfinished)
            btnSelect.background = getDrawable(R.drawable.ime_guide_activity_btn_unfinished)
            btnEnabledText.setTextColor(Color.parseColor("#FFFFFF"))
            btnSelectText.setTextColor(Color.parseColor("#FFFFFF"))
            btnEnabledimg.setImageResource(R.drawable.ime_guide_activity_btn_unfinished_img)
            btnSelectimg.setImageResource(R.drawable.ime_guide_activity_btn_unfinished_img)
            tvStep1Status.text = "Step one"
            tvStep1Status.text = "Step one"
            tvStep2Status.text = "Check to enable key of love"
        }else if(!enabled && selected){
            btnEnable.background = getDrawable(R.drawable.ime_guide_activity_btn_unfinished)
            btnSelect.background = getDrawable(R.drawable.ime_guide_activity_btn_unfinished)
            btnEnabledimg.setImageResource(R.drawable.ime_guide_activity_btn_unfinished_img)
            btnSelectimg.setImageResource(R.drawable.ime_guide_activity_btn_unfinished_img)
            btnEnabledText.setTextColor(Color.parseColor("#FFFFFF"))
            btnSelectText.setTextColor(Color.parseColor("#FFFFFF"))
            tvStep1Status.text = "Step one"
            tvStep2Status.text = "Check to enable key of love"
        }else if(enabled && !selected){
            btnEnable.background = getDrawable(R.drawable.ime_guide_activity_btn_completed)
            btnSelect.background = getDrawable(R.drawable.ime_guide_activity_btn_unfinished)
            btnEnabledimg.setImageResource(R.drawable.ime_guide_activity_btn_completed_img)
            btnSelectimg.setImageResource(R.drawable.ime_guide_activity_btn_unfinished_img)
            btnEnabledText.setTextColor(Color.parseColor("#A1A1A1"))
            btnSelectText.setTextColor(Color.parseColor("#FFFFFF"))
            tvStep1Status.text = "Step two"
            tvStep2Status.text = "Select key of love as your default input method"
        }else if(enabled && selected){
            btnEnable.background = getDrawable(R.drawable.ime_guide_activity_btn_completed)
            btnSelect.background = getDrawable(R.drawable.ime_guide_activity_btn_completed)
            btnEnabledimg.setImageResource(R.drawable.ime_guide_activity_btn_completed_img)
            btnSelectimg.setImageResource(R.drawable.ime_guide_activity_btn_completed_img)
            btnEnabledText.setTextColor(Color.parseColor("#A1A1A1"))
            btnSelectText.setTextColor(Color.parseColor("#A1A1A1"))
            tvStep1Status.text = "Completed"
            tvStep2Status.text = "You have completed the relevant Settings"
            Toast.makeText(this, "The input method is all set!", Toast.LENGTH_SHORT).show()
            startActivity(Intent(this, GuideActivity::class.java))
            finish()
        }
    }

        /** 是否启用了本输入法 */
        private fun isImeEnabled(): Boolean {
            val enabledImes = Settings.Secure.getString(
                contentResolver,
                Settings.Secure.ENABLED_INPUT_METHODS
            ) ?: return false

            // 用真正的类，而不是手写字符串
            val myImeComponent = ComponentName(this, MyInputMethodService::class.java)
            // 系统存的是 flattenToString() 的格式
            val myImeId = myImeComponent.flattenToString()

            // enabledImes 是一个用 ":" 分隔的列表
            return enabledImes.split(':').contains(myImeId)
        }

        /** 是否已切换为当前输入法 */
        private fun isImeSelected(): Boolean {
            val currentIme = Settings.Secure.getString(
                contentResolver,
                Settings.Secure.DEFAULT_INPUT_METHOD
            ) ?: return false

            val myImeComponent = ComponentName(this, MyInputMethodService::class.java)
            val myImeId = myImeComponent.flattenToString()

            // 直接用同一种格式比对
            return currentIme == myImeId
        }

}
