package com.miya.fastcashier.util

import android.app.Application
import android.content.ComponentCallbacks
import android.content.Context
import android.content.res.Configuration

class DensityUtils {

    companion object {
        var sNonCompatDensity: Float = 0f
        var sNonCompatScaledDensity: Float = 0f

        fun setDensity(context: Context, application: Application) {
            val appDisplayMetrics = application.resources.displayMetrics
            if (sNonCompatDensity == 0f) {
                sNonCompatDensity = appDisplayMetrics.density
                sNonCompatScaledDensity = appDisplayMetrics.scaledDensity
                application.registerComponentCallbacks(object : ComponentCallbacks {
                    override fun onConfigurationChanged(newConfig: Configuration) {
                        if (newConfig != null && newConfig.fontScale > 0) {
                            sNonCompatScaledDensity =
                                application.resources.displayMetrics.scaledDensity
                        }
                    }

                    override fun onLowMemory() {
                    }
                })
            }
            val targetDensity = (appDisplayMetrics.widthPixels / 720).toFloat()
            val targetScaledDensity = targetDensity * (sNonCompatScaledDensity / sNonCompatDensity)
            val targetDensityDpi = (160 * targetDensity).toInt()
            appDisplayMetrics.density = targetDensity
            appDisplayMetrics.scaledDensity = targetScaledDensity
            appDisplayMetrics.densityDpi = targetDensityDpi

            val activityDisplayMetrics = context.resources.displayMetrics
            activityDisplayMetrics.density = targetDensity
            activityDisplayMetrics.scaledDensity = targetScaledDensity
            activityDisplayMetrics.densityDpi = targetDensityDpi
        }

    }

}