package com.zxhy.fastfilemanagerpro.kokoInternalstorage

import android.content.IntentSender.OnFinished
import androidx.lifecycle.viewModelScope
import com.zxhy.fastfilemanagerpro.CommonViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class KoInternalkoViewModel : CommonViewModel() {
    fun renameFile(selectFile: File, newName: String, result: () -> Unit) {
        runCatching {
            val flag = selectFile.renameTo(File(selectFile.parentFile, newName))
            if (flag) {
                result.invoke()
            }
        }
    }

    fun copyFiles(files: List<File>, destDir: File, result: () -> Unit) =
        viewModelScope.launch(Dispatchers.IO) {
            runCatching {
                files.map {
                    if (it.isFile) {
                        it.copyTo(File(destDir, it.name), overwrite = true)
                    } else {
                        copyDirectory(it, File(destDir, it.name))
                    }
                }
            }
            result.invoke()
        }

    fun moveFiles(files: List<File>, destDir: File, result: () -> Unit) =
        viewModelScope.launch(Dispatchers.IO) {
            runCatching {
                files.map {
                    if (it.isFile) {
                        it.copyTo(File(destDir, it.name), overwrite = true)
                        it.delete()
                    } else {
                        copyDirectory(it, File(destDir, it.name))
                        deleteDirectory(it)
                    }
                }
            }
            result.invoke()
        }
}