package com.nexus.cross.sdk.unity

import android.app.Activity
import android.graphics.Rect
import android.view.ViewTreeObserver
import com.unity3d.player.UnityPlayer

/**
 * Helper that detects the soft-keyboard height.
 * Called from C# via AndroidJavaClass.CallStatic().
 */
class CROSSxKeyboardHelper {
    companion object {
        @Volatile
        private var keyboardHeightPx: Int = 0
        private var registered: Boolean = false

        @JvmStatic
        fun register() {
            if (registered) return
            val activity: Activity = UnityPlayer.currentActivity ?: return
            registered = true

            activity.runOnUiThread {
                val rootView = activity.window.decorView.rootView
                rootView.viewTreeObserver.addOnGlobalLayoutListener(
                    ViewTreeObserver.OnGlobalLayoutListener {
                        val visibleFrame = Rect()
                        rootView.getWindowVisibleDisplayFrame(visibleFrame)
                        val screenHeight = rootView.height
                        val visibleHeight = visibleFrame.bottom - visibleFrame.top
                        val diff = screenHeight - visibleHeight
                        keyboardHeightPx = if (diff > screenHeight * 0.15) diff else 0
                    }
                )
            }
        }

        @JvmStatic
        fun getKeyboardHeight(): Int = keyboardHeightPx
    }
}
