package com.doverfuelingsolutions.issp.utils.download

import android.app.DownloadManager
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Environment
import com.wayne.www.waynelib.util.log.DFSLog
import com.doverfuelingsolutions.issp.utils.thread.ThreadUtil
import java.io.File

/**
 * 下载行为类，直接下载到 Environment.DIRECTORY_DOWNLOADS 中
 */
class DownloadAction(
    val context: Context,
    uri: Uri,
    private val fileName: String,
) {

    private val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    private val request = DownloadManager.Request(uri).apply {
        DFSLog.d("download target: ${uri.path}, local name: $fileName")
        setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, fileName)
        setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION)
    }
    private var downloadId = 0L

    fun start(progressListener: ((status: Int, size: Int, total: Int) -> Unit)) {
        ThreadUtil.io {
            // 删除本地重名文件
            context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.let {
                val localFile = File("${it.absolutePath}/$fileName")
                if (localFile.exists()) localFile.delete()
            }

            // 开始下载
            downloadId = downloadManager.enqueue(request)

            // 进度
            val query = DownloadManager.Query().setFilterById(downloadId)
            var cursor: Cursor? = downloadManager.query(query)
            while (cursor != null && cursor.moveToFirst()) {
                cursor.use {
                    // 下载状态
                    val status = it.getInt(it.getColumnIndex(DownloadManager.COLUMN_STATUS))
                    // 已经下载文件大小
                    val downloaded = it.getInt(it.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
                    // 下载文件的总大小
                    val downloadTotal = it.getInt(it.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
                    DFSLog.v("apk download: status=$status, size: $downloaded, total: $downloadTotal")

                    progressListener.invoke(status, downloaded, downloadTotal)

                    cursor = when (status) {
                        DownloadManager.STATUS_PENDING, DownloadManager.STATUS_RUNNING, DownloadManager.STATUS_PAUSED -> {
                            Thread.sleep(1000)
                            downloadManager.query(query)
                        }
                        else -> {
                            null
                        }
                    }
                }
            }
        }
    }

    fun stop() {
        downloadManager.remove(downloadId)
    }
}