package com.ydl.ydlcommon.utils

import android.app.Activity
import android.app.Application
import android.content.ComponentCallbacks
import android.content.res.Configuration
import org.jetbrains.annotations.NotNull

/**
 * 屏幕适配工具类
 */
object DensityUtil{

    private var sNoncompatDensity : Float? = null
    private var sNoncompatScaledDensity : Float? = null

    /**
     *  screenWidth 设计图宽度
     */
    fun setCustonDensity(activity: Activity?,@NotNull application: Application,screenWidth : Int){

        val appDisplayMetrice = application.resources.displayMetrics
        if(sNoncompatDensity ?:0==0){
            sNoncompatDensity = appDisplayMetrice.density
            sNoncompatScaledDensity = appDisplayMetrice.scaledDensity
            application.registerComponentCallbacks(object :ComponentCallbacks{
                override fun onLowMemory() {

                }

                override fun onConfigurationChanged(newConfig: Configuration?) {
                    if(newConfig!=null && newConfig.fontScale > 0){
                        sNoncompatScaledDensity = application.resources.displayMetrics.scaledDensity
                    }
                }
            })
        }



        val targetDensity : Float = (appDisplayMetrice.widthPixels / screenWidth).toFloat()
        val targetDensityDpi = (targetDensity * 160).toInt()
        val targetScaledDensity = targetDensity*(sNoncompatScaledDensity!! / sNoncompatDensity!!)

        appDisplayMetrice.density = targetDensity
        appDisplayMetrice.densityDpi = targetDensityDpi
        appDisplayMetrice.scaledDensity = targetScaledDensity

        activity?.resources?.displayMetrics?.density = targetDensity
        activity?.resources?.displayMetrics?.densityDpi = targetDensityDpi
        activity?.resources?.displayMetrics?.scaledDensity = targetScaledDensity
    }
}