package com.xhly.manageapp.utils

import com.billbook.lib.downloader.Download
import com.billbook.lib.downloader.Downloader
import com.xhly.corelib.Const
import com.xhly.corelib.eventbus.UIEvent
import com.xhly.corelib.utils.LogShow
import com.xhly.manageapp.ManageApplication
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.io.File
import java.util.LinkedList

object AppDownLoadUtils {
    private val downloadQueue = LinkedList<Triple<String, String,String>>()

    private var isDownloading = false
    suspend fun addToDownloadQueue(url: String, appName: String,pkgName:String) {
        downloadQueue.add(Triple(url, appName,pkgName))
        if (!isDownloading) {
            startNextDownload()
        }
    }

    private suspend fun startNextDownload() {
        if (downloadQueue.isNotEmpty()) {
            val (url, appName,pkgName) = downloadQueue.removeFirst()
            downLoadFile(url, appName,pkgName)
        } else {
            isDownloading = false
        }
    }

    private suspend fun downLoadFile(url: String, appName: String,pkgName:String) {
        withContext(Dispatchers.IO) {
            try {
                //val file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                ManageApplication.instance?.let { context ->
                    var currentRetry = 0
                    var successful = false
                    while(currentRetry<3&&!successful){
                        val file = context.getExternalFilesDir(null)
                        val name = file.toString()
                        val downloader = Downloader.Builder().build()
                        val request = Download.Request.Builder()
                            .url(Const.URL1 + url)
                            .into(File(name, "$appName.apk"))
                            .build()
                        LogShow("开始下载")
                        val execute = downloader.newCall(request).execute()
                        successful = execute.isSuccessful()
                        LogShow("下载结果" + successful)
                        if (successful) {
                           /* UIEvent(Const.INSTALL_FORCEAPP).setMessage(File(name, "$appName.apk").toString()).post()*/
                           /* ManageApplication.installPackage(File(name, "$appName.apk").toString())*/
                            InstallUtils.addInstall(File(name, "$appName.apk").toString(),pkgName,appName)
                        } else {
                            currentRetry++
                        }
                        LogShow("下载后，开始安装")
                    }
                }
            } catch (e: Exception) {

            } finally {
                startNextDownload()
            }
        }
    }
}