package com.ama.core.architecture.util


import android.annotation.SuppressLint
import android.app.Activity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.doOnAttach
import kotlin.math.abs


object StatusBarUtil {


    private var statusBarHeight: Int = 0

    /**
     * 获得状态栏的高度
     * Insets 只有在 view attached 才是可用的
     */
    @SuppressLint("InternalInsetResource", "DiscouragedApi")
    fun getStatusBarHeight(activity: Activity) {
        activity.window.decorView.doOnAttach {
            /**
             * 正确获取status bar方法，通过windowInset获取
             * getInsetsIgnoringVisibility 是获取到真实高度，无论状态栏是否隐藏
             * getInsets 是根据隐藏状态获取
             */
            val ignoringVisibilityTop =
                ViewCompat.getRootWindowInsets(activity.window.decorView)?.getInsetsIgnoringVisibility(WindowInsetsCompat.Type.statusBars())?.top ?: 0
            val ignoringVisibilityBottom =
                ViewCompat.getRootWindowInsets(activity.window.decorView)?.getInsetsIgnoringVisibility(WindowInsetsCompat.Type.statusBars())?.bottom ?: 0
            statusBarHeight = abs(ignoringVisibilityTop - ignoringVisibilityBottom)
            /**
             * 兼容，系统resources可能修改
             */
            if (statusBarHeight == 0) {
                statusBarHeight = try {
                    activity.resources
                        .getIdentifier("status_bar_height", "dimen", "android")
                        .takeIf { it > 0 }
                        ?.run {
                            activity.resources.getDimensionPixelSize(this)
                        } ?: 0
                } catch (_: Exception) {
                    0
                }
            }
        }
    }
}