package com.rc.core.util

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.ComponentCallbacks
import android.content.Context
import android.content.res.Configuration
import android.util.DisplayMetrics

/**
 * 屏幕适配
 *
 * @author ReiChin_
 */
object ScreenAdapter {

    private const val DEFAULT_WIDTH = 1080 // 默认宽度

    private var appDensity = 0f

    /**
     * 字体的缩放因子，正常情况下和density相等，但是调节系统字体大小后会改变这个值
     */
    private var appScaledDensity = 0f

    /**
     * 状态栏高度
     */
    private var barHeight: Int = 0
    private var appDisplayMetrics: DisplayMetrics? = null
    private var densityScale = 1.0f

    /**
     * application 层调用，存储默认屏幕密度
     */
    fun initAppDensity(application: Application) {
        // 获取application的DisplayMetrics
        appDisplayMetrics = application.resources.displayMetrics
        // 获取状态栏高度
        barHeight = getStatusBarHeight(application)
        if (appDensity == 0f) {
            // 初始化的时候赋值
            appDensity = appDisplayMetrics!!.density
            appScaledDensity = appDisplayMetrics!!.scaledDensity
            // 添加字体变化的监听
            application.registerComponentCallbacks(object : ComponentCallbacks {

                override fun onConfigurationChanged(newConfig: Configuration) {
                    // 字体改变后,将appScaledDensity重新赋值
                    if (newConfig.fontScale > 0) {
                        appScaledDensity = application.resources.displayMetrics.scaledDensity
                    }
                }

                override fun onLowMemory() {
                }
            })
        }
    }

    /**
     * 设置自定义的屏幕密度
     */
    fun setCustomDensity(activity: Activity) {
        val targetDensity = appDisplayMetrics!!.widthPixels * 1.0f / DEFAULT_WIDTH

        // 最后在这里将修改过后的值赋给系统参数,只修改Activity的density值
        val activityDisplayMetrics = activity.resources.displayMetrics.apply {
            density = targetDensity
            scaledDensity = targetDensity * (appScaledDensity / appDensity)
            densityDpi = (160 * targetDensity).toInt()
        }

        densityScale = appDensity / targetDensity
        setBitmapDefaultDensity(activityDisplayMetrics.densityDpi)
    }

    /**
     * 重置屏幕密度
     */
    fun resetAppDensity(activity: Activity) {
        val activityDisplayMetrics = activity.resources.displayMetrics
        activityDisplayMetrics.density = appDensity
        activityDisplayMetrics.scaledDensity = appScaledDensity
        activityDisplayMetrics.densityDpi = (appDensity * 160).toInt()

        densityScale = 1.0f
        setBitmapDefaultDensity(activityDisplayMetrics.densityDpi)
    }

    /**
     * 获取状态栏高度
     *
     * @param context context
     * @return 状态栏高度
     */
    private fun getStatusBarHeight(context: Context): Int {
        val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
        return if (resourceId > 0) {
            context.resources.getDimensionPixelSize(resourceId)
        } else 0
    }

    /**
     * 设置 Bitmap 的默认屏幕密度
     * 由于 Bitmap 的屏幕密度是读取配置的，导致修改未被启用
     * 所有，放射方式强行修改
     * @param defaultDensity 屏幕密度
     */

    @SuppressLint("SoonBlockedPrivateApi")
    private fun setBitmapDefaultDensity(defaultDensity: Int) {
        try {
            // 获取单个变量的值
            val clazz = Class.forName("android.graphics.Bitmap")
            val field = clazz.getDeclaredField("sDefaultDensity")
            field.isAccessible = true
            field.set(null, defaultDensity)
            field.isAccessible = false
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 屏幕密度缩放系数
     */
    fun getDensityScale() = densityScale

}