package com.base.scanqrclear.luma

import android.os.Environment
import androidx.lifecycle.LifecycleCoroutineScope
import com.base.scanqrclear.bean.FileBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

object FileHelps {

    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
    }

    suspend fun findEmptyFolders(lifecycleScope: LifecycleCoroutineScope): MutableList<FileBean> {
        val rootDir = Environment.getExternalStorageDirectory()
        val filters = arrayOf("/storage/emulated/0/Android/data", "/storage/emulated/0/Android/obb")
        val emptyFolders = mutableListOf<File>()

        // 使用协程并发遍历文件夹
        withContext(Dispatchers.IO) {
            findEmptyFolders(lifecycleScope, rootDir, filters, emptyFolders)
        }

        return emptyFolders.map { FileBean(it.name, it.path, length = 4 * 1024) }.toMutableList()
    }

    private suspend fun findEmptyFolders(lifecycleScope: LifecycleCoroutineScope, folder: File, filters: Array<String>, emptyFolders: MutableList<File>) {
        val files = folder.listFiles() ?: return

        if (files.isEmpty() && !filters.contains(folder.path)) {
            emptyFolders.add(folder)
            return
        }

        files.filter { it.isDirectory }.map { file ->
            lifecycleScope.launch(Dispatchers.IO) {
                findEmptyFolders(lifecycleScope, file, filters, emptyFolders)
            }
        }.joinAll() // 等待所有子任务完成
    }

//    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>): List<File> {
        return root.walk()
            .filter {
                it.isDirectory && !filters.contains(it.path) && !it.isHidden && it.list()?.isEmpty() == true
            }
            .toList()
    }
}