package com.remax.visualnovel.utils


import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.widget.FrameLayout
import androidx.annotation.ColorInt
import androidx.core.graphics.ColorUtils
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.doOnAttach
import com.remax.visualnovel.R
import com.remax.visualnovel.configs.NovelApplication
import com.remax.visualnovel.constant.AppConstant
import com.remax.visualnovel.extension.findActivityContext
import timber.log.Timber
import kotlin.math.abs


object StatusBarUtils {
    private val FAKE_STATUS_BAR_VIEW_ID = R.id.fake_status_bar_view

    /**
     * 前景亮色/暗色
     * @param activity Activity
     * @param isLight Boolean  true：改为黑色
     */
    fun setStatusBarAndNavBarIsLight(activity: Activity, isLight: Boolean) {
        WindowCompat.getInsetsController(activity.window, activity.window.decorView).isAppearanceLightStatusBars = isLight
        WindowCompat.getInsetsController(activity.window, activity.window.decorView).isAppearanceLightNavigationBars = isLight
    }

    var statusBarHeight = 0
    private var navBarHeight = 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", AppConstant.ANDROID)
                        .takeIf { it > 0 }
                        ?.run {
                            activity.resources.getDimensionPixelSize(this)
                        } ?: 0
                } catch (_: Exception) {
                    0
                }
            }
        }
    }

    fun resetNavBarHeight(){
        navBarHeight = 0
    }

    /**
     * 获得下方导航栏的高度
     * 获取的是可见高度,注释见上
     */
    fun getNavBarHeight(ignoringVisibility: Boolean = false): Int {
        return if (navBarHeight == 0) {
            NovelApplication.getCurrentActivity()?.run {
                val rootWindowInsets = ViewCompat.getRootWindowInsets(window.decorView)
                val typeMask = WindowInsetsCompat.Type.navigationBars()
                val insets = if (ignoringVisibility) rootWindowInsets?.getInsetsIgnoringVisibility(typeMask) else rootWindowInsets?.getInsets(typeMask)
                val top = insets?.top ?: 0
                val bottom = insets?.bottom ?: 0
                navBarHeight = abs(bottom - top)
                Timber.d("获得下方导航栏的高度 $navBarHeight")
                navBarHeight
            } ?: 0
        } else {
            navBarHeight
        }

//            /**
//             * 野路子，暂时兼容一下，系统resources可能修改
//             */
//            if (navBarHeight == 0) {
//                val res: Resources = Resources.getSystem()
//                val resourceId: Int = res.getIdentifier("navigation_bar_height", "dimen", AppConstant.ANDROID)
//                resourceId.takeIf { it != 0 }?.run {
//                    navBarHeight = res.getDimensionPixelSize(this)
//                }
//            }
    }

    /**
     * 设置状态栏颜色
     * @param context 上下文，尽量使用Activity
     * @param color   状态栏颜色
     */
    fun setColor(context: Context, @ColorInt color: Int) {
        (context.findActivityContext() as? Activity)?.run {
            window.apply {
                addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
                statusBarColor = color
            }
            setStatusBarAndNavBarIsLight(this, !isDarkColor(color))
        }
    }

    /**
     * Android 5.0 以下版本设置状态栏颜色
     *
     * @param window        窗口
     * @param color         状态栏颜色值
     * @param isTransparent 是否透明
     */
    fun setColor(window: Window, @ColorInt color: Int, isTransparent: Boolean) {
        val context: Context = window.context
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        val decorView: ViewGroup = window.decorView as ViewGroup
        val contentView =
            decorView.findViewById<View>(android.R.id.content)
        val top = contentView?.paddingTop
        Timber.d(top.toString())
        contentView?.setPadding(0, if (isTransparent) 0 else statusBarHeight, 0, 0)
        val fakeStatusBarView =
            decorView.findViewById<View>(FAKE_STATUS_BAR_VIEW_ID)
        if (fakeStatusBarView != null) {
            fakeStatusBarView.setBackgroundColor(color)
            if (fakeStatusBarView.visibility == View.GONE) {
                fakeStatusBarView.visibility = View.VISIBLE
            }
        } else {
            // 绘制一个和状态栏一样高的矩形
            val statusBarView = View(context)
            val layoutParams = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                statusBarHeight
            )
            statusBarView.layoutParams = layoutParams
            statusBarView.setBackgroundColor(color)
            statusBarView.id = FAKE_STATUS_BAR_VIEW_ID
            decorView.addView(statusBarView)
        }
    }

    /**
     * 设置状态栏透明
     *
     * @param context 上下文，尽量使用Activity
     */
    fun setTransparent(context: Context) {
        (context.findActivityContext() as? Activity)?.run {
            this.window.apply {
                addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
                clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
                decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                statusBarColor = Color.TRANSPARENT
            }
            setStatusBarAndNavBarIsLight(this, false)
        }
    }

    /**
     * 判断颜色是否为深色
     *
     * @param color 要判断的颜色
     * @return 是否为深色
     */
    fun isDarkColor(@ColorInt color: Int) = ColorUtils.calculateLuminance(color) < 0.5

}