package com.miya.fastcashier

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.multidex.MultiDexApplication
import com.miya.print.PrinterManager
import com.tencent.mmkv.MMKV

class BaseApplication : MultiDexApplication() {
    override fun onCreate() {
        super.onCreate()
        //打印机初始化
        PrinterManager.getInstance().init(this)
        //屏幕适配
        screenAdapt()
        MMKV.initialize(this);
    }

    private fun screenAdapt() {
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                setDensity(activity, this@BaseApplication)
            }
            override fun onActivityStarted(activity: Activity) {}
            override fun onActivityResumed(activity: Activity) {}
            override fun onActivityPaused(activity: Activity) {}
            override fun onActivityStopped(activity: Activity) {}
            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
            override fun onActivityDestroyed(activity: Activity) {}
        })
    }

    fun setDensity(context: Context, application: Application) {
        val appDiaplayMetrics = application.resources.displayMetrics
        val targetDensity = (appDiaplayMetrics.widthPixels / 540).toFloat()
        val targetDensityDpi = (160 * targetDensity).toInt()
        appDiaplayMetrics.scaledDensity = targetDensity
        appDiaplayMetrics.density = appDiaplayMetrics.scaledDensity
        appDiaplayMetrics.densityDpi = targetDensityDpi
        val activityDisplayMetrics = context.resources.displayMetrics
        activityDisplayMetrics.scaledDensity = targetDensity
        activityDisplayMetrics.density = activityDisplayMetrics.scaledDensity
        activityDisplayMetrics.densityDpi = targetDensityDpi
    }
}