package com.easy.clean.utils

import android.os.Environment
import com.easy.clean.bean.FileBean
import java.io.File

object FileUtils {

    private const val WHATS_APP_MEDIA_DIR = "Android/media/com.whatsapp/WhatsApp/Media/"

    fun findWhatsappFiles(): MutableList<FileBean> {
        val rootDir = File(getAppSpecificDirPath(WHATS_APP_MEDIA_DIR))
//        val rootDir = File(getAppSpecificDirPath("Pictures/"))
        val list = findFilesRecursive(rootDir, arrayOf())
        list.sortByDescending { it.lastModified }
        return list
    }

    fun findEmptyFolders(): MutableList<FileBean> {
        val externalStorageDir = Environment.getExternalStorageDirectory()
        val filters = arrayOf("/storage/emulated/0/Android/data", "/storage/emulated/0/Android/obb")
        val emptyFolders = getAllEmptyFolders(externalStorageDir, filters)
        return emptyFolders.map { FileBean(it.name, it.path, length = 4 * 1024) }.toMutableList()
    }

    fun findTempFiles(): MutableList<FileBean> {
        val rootDir = Environment.getExternalStorageDirectory()
        return findFilesRecursive(rootDir, arrayOf(".temp"))
    }

    fun findApkFiles(): MutableList<FileBean> {
        val rootDir = Environment.getExternalStorageDirectory()
        return findFilesRecursive(rootDir, arrayOf(".apk", ".aab"))
    }

    fun findLogFiles(): MutableList<FileBean> {
        val rootDir = Environment.getExternalStorageDirectory()
        return findFilesRecursive(rootDir, arrayOf(".log"))
    }

    fun deleteFile(filePath: String) {
        File(filePath).deleteIfExists()
    }

    fun File?.deleteIfExists(): Boolean {
        if (this?.exists() == true) {
            return this.delete()
        }
        return false
    }

    private fun findFilesRecursive(dir: File, suffixes: Array<String>): MutableList<FileBean> {
        return dir.walk()
            .filter { it.isFile && it.endsWith(suffixes) }
            .map { FileBean(it.name, it.path, length = it.length(), lastModified = it.lastModified()) }
            .toMutableList()
    }

    private fun File.endsWith(suffixes: Array<String>): Boolean {
        return suffixes.isEmpty() || suffixes.any { name.lowercase().endsWith(it.lowercase()) }
    }

    private fun getAppSpecificDirPath(relativePath: String): String {
        return "${Environment.getExternalStorageDirectory()}/$relativePath"
    }

    private fun getAllEmptyFolders(root: File, filters: Array<String>): MutableList<File> {
        return root.walk()
            .filter {
                it.isDirectory && !filters.contains(it.path) && !it.isHidden && it.list()?.isEmpty() == true
            }
            .toMutableList()
    }
}