package com.img.rabbit.utils

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import androidx.core.content.FileProvider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

object UpdateUtils {
    @SuppressLint("SetTextI18n")
    fun download(scope: CoroutineScope, url: String, onProgress:(progress:Int)-> Unit, onFinish:(isSuccess: Boolean, filePath: String?)-> Unit) {
        scope.launch(Dispatchers.IO) {
            var totalProgress = 0L
            DownLoadUtils.getInstance()
                .setReadTImeOut(10L)
                .setDeleteWhenException(false)
                .initUrl(url, null)
                .setFilePath(FileUtils.getInstance().cacheDownLoderDir.absolutePath)
                .setFileName(AppUpdate.getFileNameFromUrl(url))
                .setActionCallBack(
                    { totalProgress = it },
                    {
                        val percent = it.toDouble() / totalProgress.toDouble() * 100
                        val curProgress = percent.toInt()
                        onProgress(curProgress)
                    },
                    {
                        onFinish(true, it.absolutePath)
                    }, {
                        onFinish(false, null)
                    }).down()
        }
    }

    fun install(context: Context, apkFilePath: String) {
        try {
            val apkFile = File(FileUtils.getInstance().cacheDownLoderDir, AppUpdate.getFileNameFromUrl(apkFilePath))
            if (!apkFile.exists()) {
                return
            }
            val apkUri = FileProvider.getUriForFile(context, context.packageName + ".fileProvider", apkFile)
            val intent = Intent(Intent.ACTION_VIEW)
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
            context.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}