package ta1.cis.activity

import android.Manifest
import android.app.DownloadManager
import android.content.ContentResolver
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import android.webkit.MimeTypeMap
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import kotlinx.android.synthetic.main.activity_request_izin_bermalam.*
import kotlinx.android.synthetic.main.detail_pengumuman.*
import kotlinx.android.synthetic.main.detail_pengumuman.topAppBar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.awaitResponse
import ta1.cis.R
import ta1.cis.api.Constants
import ta1.cis.api.RetrofitInstance
import ta1.cis.helper.SharedPref
import java.io.File


class DetailPengumumanActivity : AppCompatActivity() {

    private lateinit var sharedPref: SharedPref
    private lateinit var idPengumuman: String
    companion object{
        val ID_PENGUMUMAN = "ID_PENGUMUMAN"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.detail_pengumuman)
        setSupportActionBar(topAppBar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        sharedPref = SharedPref(this)
        idPengumuman = intent.getStringExtra("ID_PENGUMUMAN") as String

        fetchDetailPengumuman()

        topAppBar.setNavigationOnClickListener {
            onBackPressed()
        }
    }

    private fun fetchDetailPengumuman(){
        progressBar.visibility = View.VISIBLE
        GlobalScope.launch(Dispatchers.IO){
            val response = RetrofitInstance.instanceRetrofit.getDetailPengumuman("Bearer ${sharedPref.getTokenBearer()}",idPengumuman).awaitResponse()
            if (response.isSuccessful){
                var pengumuman = response.body()?.data
                var files = pengumuman?.files
                Log.d("DetailP",pengumuman.toString())
                withContext(Dispatchers.Main){
                    judul_pengumuman.text = pengumuman?.judul
                    deskripsi_pengumuman.settings.javaScriptEnabled
                    deskripsi_pengumuman.loadData(pengumuman?.isi.toString(),"text/html","utf-8")
//                        namafile.setText(it.namaFile)
                    tglpembuatan.setText(pengumuman!!.tglBuat)
                    tglkedaluarsa.setText(pengumuman!!.tglKadaluarsa)
                    progressBar.visibility = View.GONE
                    var count = 0;
                    files?.forEach {
                        var textView = TextView(applicationContext)
                        textView.setText(it?.namaFile)
                        textView.setId(count+1);
                        var file = it
                        Log.d("Datada",count.toString());
                        textView.setOnClickListener {
                            if (ActivityCompat.checkSelfPermission(
                                    applicationContext,
                                    Manifest.permission.READ_EXTERNAL_STORAGE
                                ) != PackageManager.PERMISSION_GRANTED
                                || ActivityCompat.checkSelfPermission(
                                    applicationContext,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                                ) != PackageManager.PERMISSION_GRANTED
                            ) {

                                // this will request for permission when user has not granted permission for the app
                                ActivityCompat.requestPermissions(
                                    this@DetailPengumumanActivity,
                                    arrayOf(
                                        Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                                    ),
                                    1
                                )
                            } else {
                                //Download Script
                                val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
                                val uri: Uri = Uri.parse(Constants.URLFileOrImage + "${file?.kodeFile}")
                                val request = DownloadManager.Request(uri)
                                var mime = getMimeType(applicationContext,uri);
                                request.setVisibleInDownloadsUi(true)
                                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                                request.setDestinationInExternalPublicDir(
                                    Environment.DIRECTORY_DOWNLOADS,
                                    file?.namaFile
                                )
                                request.setDescription("Downloading")
                                request.setAllowedOverMetered(true)
                                request.setAllowedOverRoaming(true)
                                request.setTitle("Download File ${file?.namaFile} Selesai")
                                request.setMimeType(mime)
                                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                                downloadManager.enqueue(request)
                            }
                        }
                        textView.setPadding(0,0,0,15)
                        rl_file.addView(textView)
                        count++
                    }
                }
            }
        }
    }
    fun getMimeType(context: Context, uri: Uri): String? {

        //Check uri format to avoid null
        var extension: String? = if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
            //If scheme is a content
            val mime = MimeTypeMap.getSingleton()
            mime.getExtensionFromMimeType(context.contentResolver.getType(uri))
        } else {
            //If scheme is a File
            //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
            MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(File(uri.path)).toString())
        }
        return extension
    }
//    private fun beginDownload() {
//        val url = "http://speedtest.ftp.otenet.gr/files/test10Mb.db"
//        var fileName = url.substring(url.lastIndexOf('/') + 1)
//        fileName = fileName.substring(0, 1).toUpperCase() + fileName.substring(1)
//        val file: File = Util.createDocumentFile(fileName, context)
//        val request = DownloadManager.Request(Uri.parse(url))
//            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN) // Visibility of the download Notification
//            .setDestinationUri(Uri.fromFile(file)) // Uri of the destination file
//            .setTitle(fileName) // Title of the Download Notification
//            .setDescription("Downloading") // Description of the Download Notification
//            .setRequiresCharging(false) // Set if charging is required to begin the download
//            .setAllowedOverMetered(true) // Set if download is allowed on Mobile network
//            .setAllowedOverRoaming(true) // Set if download is allowed on roaming network
//        val downloadManager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
//        downloadID =
//            downloadManager.enqueue(request) // enqueue puts the download request in the queue.
//
//        // using query method
//        var finishDownload = false
//        var progress: Int
//        while (!finishDownload) {
//            val cursor: Cursor =
//                downloadManager.query(DownloadManager.Query().setFilterById(downloadID))
//            if (cursor.moveToFirst()) {
//                val status: Int =
//                    cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
//                when (status) {
//                    DownloadManager.STATUS_FAILED -> {
//                        finishDownload = true
//                    }
//                    DownloadManager.STATUS_PAUSED -> {
//                    }
//                    DownloadManager.STATUS_PENDING -> {
//                    }
//                    DownloadManager.STATUS_RUNNING -> {
//                        val total: Long =
//                            cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
//                        if (total >= 0) {
//                            val downloaded: Long =
//                                cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
//                            progress = (downloaded * 100L / total).toInt()
//                            // if you use downloadmanger in async task, here you can use like this to display progress.
//                            // Don't forget to do the division in long to get more digits rather than double.
//                            //  publishProgress((int) ((downloaded * 100L) / total));
//                        }
//                    }
//                    DownloadManager.STATUS_SUCCESSFUL -> {
//                        progress = 100
//                        // if you use aysnc task
//                        // publishProgress(100);
//                        finishDownload = true
//                        Toast.makeText(this@MainActivity, "Download Completed", Toast.LENGTH_SHORT)
//                            .show()
//                    }
//                }
//            }
//        }
//    }
}