package com.cheng.blzb.utils

import android.annotation.SuppressLint
import com.example.base.utils.Utils
import java.io.File


object DataCacheUtils {

    /**
     * 获取缓存大小
     */
    fun getCacheSize(): Long {
        return getDirectorySize(com.cheng.blzb.utils.FileUtils.getInstance().cacheDir)
    }

    /**
     * 清除本应用内部缓存
     */
    fun cleanInternalCache() {
        deleteFilesByDirectory(com.cheng.blzb.utils.FileUtils.getInstance().cacheDir, false)
    }

    /**
     * 获取文件夹大小
     *
     * @param directory
     */
    private fun getDirectorySize(directory: File): Long {
        var size: Long = 0
        val files = directory.listFiles()
        if (files != null) {
            for (file in files) {
                size += if (file.isFile()) {
                    file.length()
                } else {
                    getDirectorySize(file)
                }
            }
        }
        return size
    }

    /**
     * * 删除文件夹下的所有文件
     *
     * @param directory
     */
    private fun deleteFilesByDirectory(directory: File, deleteDir: Boolean = true): Boolean {
        if (directory.isDirectory()) {
            val children = directory.list()
            if (children != null) {
                for (i in children.indices) {
                    val success = deleteFilesByDirectory(File(directory, children[i]))
                    if (!success) {
                        return false
                    }
                }
            }
        }
        return !deleteDir || directory.delete()
    }

    /**
     * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs)
     *
     */
    @SuppressLint("SdCardPath")
    fun cleanSharedPreference() {
        deleteFilesByDirectory(File("/data/data/${Utils.getApp().packageName}/shared_prefs"))
    }
}