package com.khmer9.cflivemain.app

import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.widget.Toast
import androidx.core.content.FileProvider
import com.khmer9.cflivemain.R
import com.khmer9.cflivemain.config.Config
import com.khmer9.cflivemain.screen.main.PackageChangeReceiver
import java.io.File


class DownloadController(private val context: Context, private val url: String, private val token: String? = null) {
    companion object {
        private const val FILE_NAME = "SampleDownloadApp.apk"
        private const val FILE_BASE_PATH = "file://"
        private const val MIME_TYPE = "application/vnd.android.package-archive"
        private const val PROVIDER_PATH = ".provider"
        private const val APP_INSTALL_PATH = "\"application/vnd.android.package-archive\""
    }

    fun enqueueDownload() {
        var destination =
            context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + "/"
        destination += FILE_NAME
        val uri = Uri.parse("$FILE_BASE_PATH$destination")
        val file = File(destination)
        if (file.exists()) file.delete()
        val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        val downloadUri = Uri.parse(url)
        val request = DownloadManager.Request(downloadUri)
        request.setMimeType(MIME_TYPE)
        request.setTitle(context.getString(R.string.title_file_download))
        request.setDescription(context.getString(R.string.downloading))
        // set destination
        request.setDestinationUri(uri)
        showInstallOption(destination, uri)
        // Enqueue a new download and same the referenceId
        downloadManager.enqueue(request)
        Toast.makeText(context, context.getString(R.string.downloading), Toast.LENGTH_LONG)
            .show()
    }

    private fun showInstallOption(
        destination: String,
        uri: Uri
    ) {
        // set BroadcastReceiver to install app when .apk is downloaded
        val onComplete = object : BroadcastReceiver() {
            override fun onReceive(
                context: Context,
                intent: Intent
            ) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    val contentUri = FileProvider.getUriForFile(
                        context,
                        Config.MAIN_PACKAGE + PROVIDER_PATH,
                        File(destination)
                    )
                    val install = Intent(Intent.ACTION_VIEW)
                    install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    install.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    install.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true)
                    install.putExtra(Intent.EXTRA_RETURN_RESULT, true)
                    install.data = contentUri
                    Toast.makeText(context, "ដោនឡូតបានជោគជ័យ", Toast.LENGTH_LONG).show()

                    val bundle = Bundle()
                    bundle.putString("token", token)
                    install.putExtra("token", bundle)

                    context.unregisterReceiver(this)
                    (context as ShareActivity).apply {
                        startActivity(install)
                        PackageChangeReceiver.token = token
                        //finish()
                    }
                } else {
                    val install = Intent(Intent.ACTION_VIEW)
                    install.putExtra(Intent.EXTRA_RETURN_RESULT, true)
                    install.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                    install.setDataAndType(
                        uri,
                        APP_INSTALL_PATH
                    )

                    Toast.makeText(context, "ដោនឡូតបានជោគជ័យ", Toast.LENGTH_LONG).show()

                    val bundle = Bundle()
                    bundle.putString("token", token)
                    install.putExtra("token", bundle)

                    context.unregisterReceiver(this)
                    (context as ShareActivity).apply {
                        startActivity(install)
                        PackageChangeReceiver.token = token
                        //finish()
                    }
                }
            }
        }
        context.registerReceiver(onComplete, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
    }
}