package com.base.scanqrclear.luma

import android.app.ActivityManager
import android.content.Context
import android.os.Environment
import android.os.StatFs

object AppHelps {

    fun getMemTotal(context: Context): Long {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)
        return memoryInfo.totalMem
    }

    fun getMemAvailable(context: Context): Long {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)
        return memoryInfo.availMem
    }

    fun getTotalExternalSize(): Long {
        try {
            val statFs = StatFs(Environment.getExternalStorageDirectory().path)
            val statFs2 = StatFs(Environment.getRootDirectory().path)
            val blockSizeLong =
                statFs2.blockSizeLong * statFs2.blockCountLong + statFs.blockSizeLong * statFs.blockCountLong
            return calculateTotalExternal(blockSizeLong)
        } catch (e: Exception) {
            return 0
        }
    }

    fun getAvailableExternalSize(): Long {
        try {
            val statFs = StatFs(Environment.getExternalStorageDirectory().path)
            val statFs2 = StatFs(Environment.getRootDirectory().path)
            val blackSize =
                statFs2.blockSizeLong * statFs2.availableBlocksLong + statFs.blockSizeLong * statFs.availableBlocksLong
            return calculateAvailableExternal(blackSize)
        } catch (e: Exception) {
            return 0
        }
    }

    private fun calculateTotalExternal(size: Long): Long {
        var powerOfTwo: Long = 1
        while (powerOfTwo < size) {
            powerOfTwo *= 2
        }
        return powerOfTwo
    }

    private fun calculateAvailableExternal(size: Long): Long {
        var value = size
        var n = 0
        while (true) {
            val m: Long = 1000
            if (value < m) {
                break
            }
            value /= m
            n++
        }
        for (i in 0 until n) {
            value *= 1024
        }
        return value
    }

    fun Context.dpToPx(dp: Int): Float {
        val density = resources.displayMetrics.density
        return dp * density
    }
}