import android.content.Context
import android.text.format.DateUtils
import android.util.Log
import java.io.File
import java.util.Date


object HttpCacheUtil {
    private const val TAG = "HttpCacheUtil"

    /**
     * 缓存大小 10M
     */
    private const val CACHESIZE = 1024 * 1024 * 10L

    /**
     * Delete the files older than numDays days from the application cache
     * 0 means all files.
     * @param context
     * @param numDays
     */
    fun clearCache(context: Context, numDays: Int) {
        Log.i(
            TAG,
            String.format("Starting cache prune, deleting files older than %d days", numDays)
        )
        val numDeletedFiles = clearCacheFolder(context.cacheDir, numDays)
        Log.i(TAG, String.format("Cache pruning completed, %d files deleted", numDeletedFiles))
//        Toast.makeText(context, "缓存已经清除！", Toast.LENGTH_SHORT).show()
    }

    //helper method for clearCache() , recursive
    //returns number of deleted files
    private fun clearCacheFolder(dir: File?, numDays: Int): Int {
        var deletedFiles = 0
        if (dir != null && dir.isDirectory) {
            Log.i(TAG, "cache dir:" + dir.absolutePath)
            try {
                for (child in dir.listFiles()) {

                    //first delete subdirectories recursively
                    if (child.isDirectory) {
                        deletedFiles += clearCacheFolder(child, numDays)
                    }

                    //then delete the files and subdirectories in this dir
                    //only empty directories can be deleted, so subdirs have been done first
                    if (child.lastModified() <= Date().time - numDays * DateUtils.DAY_IN_MILLIS) {
                        if (child.delete()) {
                            deletedFiles++
                        }
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, String.format("Failed to clean the cache, error %s", e.message))
            }
        }
        return deletedFiles
    }
}