package com.ccwangluo.accelerator.manager

import android.Manifest
import android.app.DownloadManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.webkit.MimeTypeMap
import androidx.core.content.FileProvider
import androidx.fragment.app.FragmentActivity
import com.ccwangluo.accelerator.ui.dialog.DownloadDialog
import com.hjq.toast.ToastUtils
import com.xuexiang.xutil.system.PermissionUtils
import java.io.File


object DownloadUtils {

    fun downloadFile(activity: FragmentActivity, url: String) {
        if(url.isNullOrBlank()){
            return
        }
        if (!PermissionUtils.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            ToastUtils.show("下载需要打开存储权限")
            PermissionUtils.permission(Manifest.permission.WRITE_EXTERNAL_STORAGE.toString())
                .rationale({
                    PermissionUtils.openAppSettings()
                }).request()
            return
        }
        var filename = url.split("/").last()
        var file = File(
            activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),
            filename
        )

        if (file.exists()) {
            install(file.absolutePath, activity)
            return
        }
        val downloadManager = activity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        val request =
            DownloadManager.Request(Uri.parse(url)) //添加下载文件的网络路径

        request.setDestinationInExternalFilesDir(activity,Environment.DIRECTORY_DOWNLOADS,filename)
        val mimeTypeMap = MimeTypeMap.getSingleton()
        val mimeString =
            mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url))
        request.setMimeType(mimeString)

        request.setTitle("下载中") //添加在通知栏里显示的标题
//        request.setDescription("下载中") //添加在通知栏里显示的描述

        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE or DownloadManager.Request.NETWORK_WIFI) //设置下载的网络类型

        request.setVisibleInDownloadsUi(false) //是否显示下载 从Android Q开始会被忽略

        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) //下载中与下载完成后都会在通知中显示| 另外可以选 DownloadManager.Request.VISIBILITY_VISIBLE 仅在下载中时显示在通知中,完成后会自动隐藏

        val id = downloadManager.enqueue(request) //加入队列，会返回一个唯一下载id

        DownloadDialog(activity, downloadManager, id).show()
    }


    /**
     * 描述: 安装
     */
    fun install(apkPath: String, context: Context): Boolean {
        // 没有root权限，利用意图进行安装
        val file = File(apkPath)
        if (!file.exists()) {
            return false
        }
        val intent = Intent(Intent.ACTION_VIEW)
        val uri: Uri
        val type = "application/vnd.android.package-archive"
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            uri = Uri.fromFile(file)
        } else {
            val authority = "com.ccwangluo.accelerator.fileprovider"
            uri = FileProvider.getUriForFile(context, authority, file)
            intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
        }
        context.grantUriPermission(
            context.packageName,
            uri,
            Intent.FLAG_GRANT_READ_URI_PERMISSION
        )
        intent.setDataAndType(uri, type)
        //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
        return true
    }
}