package  com.atmob.keyboard_android.keyboard

import android.app.Activity
import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import com.atmob.keyboard_android.util.InputMethodUtil
import com.atmob.keyboard_android.util.LogUtil

/**
 * 选择输入法的页面，是一个透明的Activity，用于触发系统的输入法选择器，选择完就自动关闭
 */
class InputMethodPickerActivity : Activity() {
    private var isFirst = true

    private val mMainHandler = Handler(Looper.getMainLooper())

    companion object {
        /**
         * 启动
         */
        fun start(context: Context) {
            val intent = Intent(context, InputMethodPickerActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
            val options = ActivityOptions.makeCustomAnimation(context, 0, 0)
            context.startActivity(intent, options.toBundle())
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 设置无动画启动
        overridePendingTransition(0, 0)
    }

    override fun onDestroy() {
        super.onDestroy()
        mMainHandler.removeCallbacksAndMessages(null)
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        LogUtil.d("onWindowFocusChanged focus=$hasFocus, first=$isFirst")

        if (!hasFocus) {
            return
        }

        if (isFirst) {
            isFirst = false
            //为了确保 Activity 完全进入前台后再弹出输入法选择器
            mMainHandler.postDelayed({
                LogUtil.d("showInputMethodPicker triggered")
                InputMethodUtil.showInputMethodPicker(applicationContext)
            }, 100)
        } else {
            // 第二次获得焦点代表输入法弹窗消失
            LogUtil.d("InputMethodPicker dismissed, finishing activity")
            finish()
        }
    }

    override fun finish() {
        // 关闭时也不使用动画
        overridePendingTransition(0, 0)
        super.finish()
    }
}