package com.xhly.corelib.utils

import android.app.usage.StorageStatsManager
import android.content.Context
import android.os.Build
import android.os.storage.StorageManager
import androidx.appcompat.app.AppCompatActivity
import java.text.DecimalFormat

class FileSizeUtils {
    companion object{
        fun getTotalSpace(context: Context): Long {
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val storageStatsManager =
                    context.getSystemService(AppCompatActivity.STORAGE_STATS_SERVICE) as StorageStatsManager
                storageStatsManager.getTotalBytes(StorageManager.UUID_DEFAULT)
            }else{
                context.filesDir.totalSpace
            }
        }

        fun getFreeSpace(context: Context): Long {
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val storageStatsManager =
                    context.getSystemService(AppCompatActivity.STORAGE_STATS_SERVICE) as StorageStatsManager
                storageStatsManager.getFreeBytes(StorageManager.UUID_DEFAULT)
            }else{
                context.filesDir.freeSpace
            }
        }
        private val fileIntegerFormat = DecimalFormat("#0")
        private val fileDecimalFormat = DecimalFormat("#0.#")
        fun formatFileSize(size: Long, isInteger: Boolean=false): String {
            val unit = 1000
            val df = if (isInteger) fileIntegerFormat else fileDecimalFormat
            var fileSizeString = "0M"
            fileSizeString = if (size < unit && size > 0) {
                df.format(size.toDouble()) + "B"
            } else if (size < unit * unit) {
                df.format(size.toDouble() / unit) + "K"
            } else if (size < unit * unit * unit) {
                df.format(size.toDouble() / (unit * unit)) + "M"
            } else {
                df.format(size.toDouble() / (unit * unit * unit)) + "G"
            }
            return fileSizeString
        }
    }
}