package com.zxhy.simplefilesmanager.simpleCommon

import android.content.Context
import android.os.Environment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zxhy.simplefilesmanager.simpledata.JoFileJo
import com.zxhy.simplefilesmanager.simpledata.JoGridFileJo
import com.zxhy.simplefilesmanager.simpledata.JoGridFileJo.Companion.joGridFileJo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import java.util.LinkedList
import kotlin.reflect.KFunction0

abstract class SimpleCommonViewModel : ViewModel() {

    private fun linkedWhileFolder(folder: File, onDo: ((file: File) -> Unit)?) {

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

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


    fun deleteFiles(files: List<File>, action: () -> Unit) =
        viewModelScope.launch(Dispatchers.IO) {
            runCatching {
                files.forEach {
                    if (it.exists()) it.delete()
                }
                action.invoke()
            }
        }

    /**
     * @param filter 过滤条件
     * @param convert 抓换为JoFileJo的转换方法
     * @param onDo 扫描部分数据执行
     * @param onFinish 扫描完成执行
     */
    fun <T : JoFileJo> loadFile(
        filter: (file: File) -> Boolean,
        convert: (file: File) -> T,
        onDo: (list: List<T>) -> Unit,
        onFinish: (list: List<T>) -> Unit
    ) = viewModelScope.launch(Dispatchers.IO) {
        val root = Environment.getExternalStorageDirectory()
        val resultList = arrayListOf<T>()
        var firstSend = false

        linkedWhileFolder(root) { file ->
            if (filter(file)) {
                resultList.add(convert(file))
                if (resultList.size == 20 && !firstSend) {
                    val mainList = arrayListOf<T>()
                    mainList.addAll(resultList)
                    //这里onDo切换到main主协程,避免IO协程里的数据和main协程里的数据共用同一对象
                    onDo.invoke(mainList)
                    resultList.clear()
                    firstSend = true
                }
            }
        }
        onFinish.invoke(resultList)
    }

}