package com.convenient.android.common.utils.systemui

import android.app.Activity
import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener


typealias KeyBoardShow = (height: Int) -> Unit
typealias KeyBoardHide = (height: Int) -> Unit

/**
 *    @author : hubowen
 *    @date   : 2020/11/6  7:03 PM
 *    @description：软键盘打开显示隐藏监听
 */
class SoftKeyBoardUtils(activity: Activity) {
    //activity的根视图
    private val rootView: View = activity.window.decorView

    //纪录根视图的显示高度
    var rootViewVisibleHeight: Int

    private var keyBoardShow : KeyBoardShow? = null

    private var keyBoardHide : KeyBoardHide? = null

    private fun setOnSoftKeyBoardChangeListener(show: KeyBoardShow, hide: KeyBoardHide) {
        this.keyBoardShow = show
        this.keyBoardHide = hide
    }


    companion object {
        fun setListener(activity: Activity, show: KeyBoardShow , hide: KeyBoardHide) {
            val softKeyBoardListener = SoftKeyBoardUtils(activity)
            softKeyBoardListener.setOnSoftKeyBoardChangeListener(show, hide)
        }

    }

    init {
        //获取activity的根视图
        val r = Rect()
        rootView.getWindowVisibleDisplayFrame(r)
        rootViewVisibleHeight = r.height()
        //监听视图树中全局布局发生改变或者视图树中的某个视图的可视状态发生改变
        rootView.viewTreeObserver.addOnGlobalLayoutListener(OnGlobalLayoutListener { //获取当前根视图在屏幕上显示的大小
            val r = Rect()
            rootView.getWindowVisibleDisplayFrame(r)
            val visibleHeight: Int = r.height()
            println("" + visibleHeight)
            if (rootViewVisibleHeight == 0) {
                rootViewVisibleHeight = visibleHeight
                return@OnGlobalLayoutListener
            }

            //根视图显示高度没有变化，可以看作软键盘显示／隐藏状态没有改变
            if (rootViewVisibleHeight == visibleHeight) {
                return@OnGlobalLayoutListener
            }

            //根视图显示高度变小超过200，可以看作软键盘显示了
            if (rootViewVisibleHeight - visibleHeight > 200) {
                keyBoardShow?.invoke(rootViewVisibleHeight - visibleHeight)
                rootViewVisibleHeight = visibleHeight
                return@OnGlobalLayoutListener
            }

            //根视图显示高度变大超过200，可以看作软键盘隐藏了
            if (visibleHeight - rootViewVisibleHeight > 200) {
                keyBoardHide?.invoke(visibleHeight - rootViewVisibleHeight)
                rootViewVisibleHeight = visibleHeight
                return@OnGlobalLayoutListener
            }
        })
    }
}