package com.atmob.keyboard_android.util

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import java.util.concurrent.CopyOnWriteArrayList


/**
 * 默认键盘切换监听器
 */
@SuppressLint("StaticFieldLeak")
object DefaultKeyboardWatcher {
    /**
     * 是否初始化了
     */
    private var isInited = false

    private val mContext = ContextUtil.getContext()

    /**
     * 监听器列表
     */
    private val mListenerList = CopyOnWriteArrayList<OnDefaultKeyboardChangeListener>()

    /**
     * 初始化，注册监听
     */
    fun init() {
        val filter = IntentFilter(Intent.ACTION_INPUT_METHOD_CHANGED)
        mContext.registerReceiver(mImeChangeReceiver, filter)
        isInited = true
    }

    /**
     * 解注册，注销监听
     */
    fun unInit() {
        mContext.unregisterReceiver(mImeChangeReceiver)
        isInited = false
    }

    /**
     * 是否初始化了
     */
    fun isInited(): Boolean {
        return isInited
    }

    interface OnDefaultKeyboardChangeListener {
        /**
         * 当前键盘，被设置为默认键盘时回调
         */
        fun onDefaultKeyboard()

        /**
         * 当前键盘，非默认键盘时回调
         */
        fun onNotDefaultKeyboard()
    }

    /**
     * 默认软键盘，切换监听
     */
    private val mImeChangeReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            if (Intent.ACTION_INPUT_METHOD_CHANGED == intent.action) {
                // 当前键盘，被设置为默认键盘
                if (InputMethodUtil.isDefaultKeyboard(mContext)) {
                    for (listener in mListenerList) {
                        listener.onDefaultKeyboard()
                    }
                } else {
                    // 当前键盘，非默认键盘
                    for (listener in mListenerList) {
                        listener.onNotDefaultKeyboard()
                    }
                }
            }
        }
    }

    /**
     * 注册监听器
     */
    fun registerListener(listener: OnDefaultKeyboardChangeListener) {
        if (!mListenerList.contains(listener)) {
            mListenerList.add(listener)
        }
    }

    /**
     *
     */
    fun unRegisterListener(listener: OnDefaultKeyboardChangeListener) {
        mListenerList.remove(listener);
    }
}