package com.base.browserwhite.utils

import android.annotation.SuppressLint
import android.app.DownloadManager
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Environment
import com.base.browserwhite.R
import java.io.File


object VideoDownloader {

    //https://assets.mixkit.co/videos/4702/4702-720.mp4
    fun downloadVideo(context: Context, uri: String, name: String): Pair<Long, File> {
        val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

        var fileName = uri.split("/").last()
        if (name.isNotEmpty()) {
            fileName = name
        }


        // 创建一个DownloadManager.Request对象
        val request = DownloadManager.Request(Uri.parse(uri))

        // 设置下载的标题和描述
        request.setTitle(fileName)
        request.setDescription("Downloading $fileName")

        // 设置通知栏的可见性
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)

        // 设置下载的文件类型
        request.setMimeType("video/mp4")

        // 设置下载文件的存储位置
        val subPath = context.resources.getString(R.string.app_name) + "/$fileName"
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, subPath)

        // 设置是否允许漫游
        request.setAllowedOverRoaming(false)

        // 将下载请求加入下载队列
        val downloadId = downloadManager.enqueue(request)

        val filePath = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), subPath)

        return Pair(downloadId, filePath)
    }

    fun queryDownloadProgress(
        context: Context,
        downloadId: Long,
        uiAction: (progress: Int) -> Unit,
        noRunningAction: (status: Int) -> Unit
    ) {
        if (downloadId == -1L) {
            return noRunningAction.invoke(-1)
        }

        val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

        // 创建查询对象
        val query = DownloadManager.Query().setFilterById(downloadId)

        // 执行查询
        val cursor = downloadManager.query(query)

        // 检查游标是否有数据
        if (cursor != null && cursor.moveToFirst()) {
            // 获取下载的状态
            val columnIndexStatus = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)
            val status = cursor.getInt(columnIndexStatus)

            // 检查下载是否还在进行中
            if (status == DownloadManager.STATUS_RUNNING) {
                // 获取下载的进度
                val columnIndexBytesDownloadedSoFar = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
                val bytesDownloadedSoFar = cursor.getLong(columnIndexBytesDownloadedSoFar)

                val columnIndexTotalSizeBytes = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
                val totalSizeBytes = cursor.getLong(columnIndexTotalSizeBytes)

                // 计算下载的百分比
                val progress = (100 * bytesDownloadedSoFar.toFloat() / totalSizeBytes.toFloat()).toInt()

                // 在这里处理进度更新，例如更新UI
                uiAction.invoke(progress)

            } else {
                // 处理下载完成或出错的情况
                noRunningAction.invoke(status)
                when (status) {
                    DownloadManager.STATUS_PAUSED -> {
                        println("Download paused")
                    }

                    DownloadManager.STATUS_FAILED -> {
                        println("Download failed")
                    }

                    DownloadManager.STATUS_SUCCESSFUL -> {
                        println("Download successful")
                    }
                }
            }

            // 关闭游标
            cursor.close()
        }
    }

    @SuppressLint("Range")
    fun queryDownloadFilePath(context: Context, downloadId: Long): String {
        var filePath: String = ""
        val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

        runCatching {
            val query = DownloadManager.Query().setFilterById(downloadId)
            val cursor: Cursor = downloadManager.query(query)
            if (cursor.moveToFirst()) {
                val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
                if (status == DownloadManager.STATUS_SUCCESSFUL) {
                    //下载文件的本地路径
                    filePath = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME))
                }
            }
            cursor.close()
        }
        return filePath
    }
}