package com.base.pdfviewerscannerwhite.utils

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableSharedFlow
import java.io.File
import java.util.LinkedList

object FileHelp {
    fun CoroutineScope.getFileFolder(
        flow: MutableSharedFlow<String>? = null,
        file: File,
        filter: (file: File) -> Boolean
    ) = async(Dispatchers.IO) {

        val set = HashSet<File>()
        //添加第一层文件到链表
        val linkList = LinkedList<File>()
        val fileList = file.listFiles()
        fileList?.forEach {
            if (it.isDirectory) {
                flow?.emit(it.absolutePath)
                linkList.add(it)
                if (filter.invoke(it)) {
                    set.add(it)
                }
            }
        }

        //链表取文件
        var tempFile: File
        while (!linkList.isEmpty()) {
            tempFile = linkList.removeFirst()
            val tempFileList = tempFile.listFiles()
            tempFileList?.forEach {
                if (it.isDirectory) {
                    flow?.emit(it.absolutePath)
                    linkList.add(it)
                    if (filter.invoke(it)) {
                        set.add(it)
                    }
                }
            }
        }
        set.toList()
    }


    fun getFileFolder(
        file: File,
        filter: (file: File) -> Boolean
    ): List<File> {

        val set = HashSet<File>()
        //添加第一层文件到链表
        val linkList = LinkedList<File>()
        val fileList = file.listFiles()
        fileList?.forEach {
            if (it.isDirectory) {
                linkList.add(it)
                if (filter.invoke(it)) {
                    set.add(it)
                }
            }
        }

        //链表取文件
        var tempFile: File
        while (!linkList.isEmpty()) {
            tempFile = linkList.removeFirst()
            val tempFileList = tempFile.listFiles()
            tempFileList?.forEach {
                if (it.isDirectory) {
                    linkList.add(it)
                    if (filter.invoke(it)) {
                        set.add(it)
                    }
                }
            }
        }
        return set.toList()
    }
}