package com.ccwangluo.accelerator.ui.dialog


import android.app.DownloadManager
import android.content.DialogInterface
import android.database.Cursor
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.hjq.toast.ToastUtils
import com.xuexiang.xui.widget.dialog.materialdialog.GravityEnum
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class DownloadDialog(
    val context: FragmentActivity,
    val downloadManager: DownloadManager,
    var downloadId: Long
) {
    fun show() {
        val dialog = MaterialDialog.Builder(context)
            .content("下载中")
            .contentGravity(GravityEnum.CENTER)
            .progress(false, 100, true)
            .cancelListener(
                { ToastUtils.show("下载中") })
            .cancelable(false)
            .negativeText("隐藏")
            .onPositive { dialog, which ->
                cancellDownload()
            }
            .positiveText("取消")
            .showListener({})
            .show()
        context.lifecycleScope.launch(Dispatchers.IO) {
            while (dialog.progressBar.progress < 100 && dialog.isShowing) {
                val progress = getDownloadProgress()
                withContext(Dispatchers.Main) {
                    dialog.setProgress(progress.toInt())
                }
                delay(500)
            }
            withContext(Dispatchers.Main) {
                if (dialog.isShowing) {
                    dialog.dismiss()
                }
            }

        }

    }

    fun cancellDownload() {
        try {
            downloadManager.remove(downloadId)
        } catch (e: Exception) {

        }
    }

    fun getDownloadProgress(): Float {
        val query = DownloadManager.Query().setFilterById(downloadId)
        val c: Cursor = downloadManager.query(query)
        if (c != null) {
            try {
                if (c.moveToFirst()) {
                    val mDownload_so_far =
                        c.getInt(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
                    val mDownload_all =
                        c.getInt(c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
                    println("mDownload_so_far = $mDownload_so_far   &&& mDownload_all = ${mDownload_all}  &&& ${mDownload_so_far * 100 / mDownload_all} ")
                    return (mDownload_so_far.toFloat() / mDownload_all) * 100
                }
            } finally {
                c.close()
            }
        }
        return -1F
    }
}
