package com.xhly.manageapp.utils

import android.app.Activity
import com.hjq.toast.Toaster
import com.xhly.corelib.utils.LogShow
import com.xhly.manageapp.ManageApplication
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.LinkedList
import java.util.Queue

object InstallUtils {
    var isRunning: Boolean = false
    var isInstalling: Boolean = false
    val queue: Queue<InstallItem> = LinkedList()
    var coroutineScope:CoroutineScope? = null
    fun installSuccess(packageName: String) {
        LogShow("执行任务"+packageName)
        if (queue.size > 0) {
            LogShow("111执行任务"+packageName)
            val installItem = queue.peek()
            if (installItem != null) {
                LogShow("222执行任务"+packageName)
                if(packageName == installItem.packageName){
                    LogShow("333执行任务"+packageName)
                    queue.poll()
                    isInstalling = false
                }
            }
        }
    }

    fun addInstall(savepath: String, packageName: String,appName: String) {
        var isHave = false
        for (element in queue) {
            if (element.packageName === packageName) {
                isHave = true
            }
        }
        if (!isHave) {
            queue.add(InstallItem( savepath, packageName,appName))
        }
        installAction()
    }

    private fun installAction() {
        LogShow("开始安装"+ isRunning)
        if (isRunning) {
            return
        }
        if (coroutineScope==null){
            coroutineScope=CoroutineScope(Dispatchers.IO)
        }
        coroutineScope?.launch {
            while (queue.size > 0) {
                isRunning = true
                val installItem = queue.peek()
                installItem?.let {
                    isInstalling = true
                    //installApp(installItem.activity, installItem.savepath, installItem.packageName)
                    withContext(Dispatchers.Main){
                        Toaster.show(installItem.appName+"正在安装")
                        ManageApplication.installPackage(installItem.savepath)
                    }
                    while (isInstalling) {
                        delay(1000)
                    }
                }
            }
            isRunning = false
        }

    }

    public fun destroyInstallUtils(){
        queue.clear()
        isRunning= false
        isInstalling = false
        coroutineScope?.cancel()
        LogShow("任务取消")
    }
}

data class InstallItem(val savepath: String, val packageName: String,val appName:String)