package com.base.scanqr.ui.vm

import android.content.Context
import android.os.Environment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.base.scanqr.R
import com.base.scanqr.utils.ToastUtils.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class QrViewModel : ViewModel() {

    fun copyFileToDownloads(context: Context, name: String, copyTempPath: String) = viewModelScope.launch(Dispatchers.IO) {
        val appFile = File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
            context.resources.getString(R.string.app_name)
        )
        if (!appFile.exists()) appFile.mkdirs()

        var newName = name
        if (!name.endsWith(".jpg")) {
            newName = "$name.jpg"
        }
        val downFile = File(appFile, newName)
        val flag = downFile.createNewFile()
        if (flag) {
            File(copyTempPath).copyTo(downFile, true)
            launch(Dispatchers.Main) {
                context.toast("Save to:${appFile.absolutePath}", true)
            }
        }
    }
}