package `in`.webgrid.generp
import android.app.DownloadManager
import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.webkit.CookieManager
import android.widget.Toast
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity(){
    private val CHANNEL = "in.webgrid.generp/download"
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "startDownload") {
                val url = call.argument<String>("url")
                val userAgent = call.argument<String>("userAgent")
                val contentDisposition = call.argument<String>("contentDisposition")
                val mimeType = call.argument<String>("mimeType")
                val suggestedFilename = call.argument<String>("suggestedFilename")

                if (url != null && userAgent != null && mimeType != null) {
                    val success = startDownload(url, userAgent, contentDisposition ?: "", mimeType,suggestedFilename ?: "")
                    if (success) {
                        result.success("Download started")
                    } else {
                        result.error("DOWNLOAD_FAILED", "Failed to start download", null)
                    }
                } else {
                    result.error("INVALID_ARGUMENTS", "Missing required arguments", null)
                }
            } else {
                result.notImplemented()
            }
        }
    }

    private fun startDownload(url: String, userAgent: String, contentDisposition: String, mimeType: String, suggestedFilename: String): Boolean {
        return try {
            // Show toast
            Toast.makeText(this, "File is being downloaded", Toast.LENGTH_SHORT).show()

            // Initialize download request
            val request = DownloadManager.Request(Uri.parse(url.trim()))

            // Get cookies
            val cookies = CookieManager.getInstance().getCookie(url) ?: ""
            request.addRequestHeader("Cookie", cookies)
            request.addRequestHeader("User-Agent", userAgent)

            // Set description
            request.setDescription("Downloading requested file....")

            // Set MIME type
            request.setMimeType(mimeType)

            // Allow scanning by media scanner
            request.allowScanningByMediaScanner()

            // Set notification visibility
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)

            // Map MIME type to file extension
            val extension = when (mimeType.lowercase()) {
                "application/pdf" -> ".pdf"
                "image/jpeg" -> ".jpg"
                "image/png" -> ".png"
                "application/msword" -> ".doc"
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document" -> ".docx"
                "application/vnd.ms-excel" -> ".xls"
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" -> ".xlsx"
                else -> ".bin" // Fallback for unknown types
            }

            // Guess file name
//            val fileName = contentDisposition.takeIf { it.isNotEmpty() }?.let {
//                // Parse contentDisposition to extract filename if needed
//                it.split(";").find { it.trim().startsWith("filename=") }
//                    ?.substringAfter("filename=")?.trim('"')
//            } ?: url.split("/").last()
            var fileName = contentDisposition.takeIf { it.isNotEmpty() }?.let {
                // Parse Content-Disposition header (e.g., attachment; filename="Genesis_Quote_70772_16_May_2025_03_17.pdf")
                val regex = Regex("filename=\"?([^\"\\s;]+)\"?")
                regex.find(it)?.groupValues?.get(1)
            } ?: suggestedFilename.takeIf { it.isNotEmpty() } ?: url.split("/").last()
            // Ensure the file name has the correct extension
            if (!fileName.endsWith(extension, ignoreCase = true)) {
                fileName = if (fileName.contains(".")) {
                    fileName.substringBeforeLast(".") + extension
                } else {
                    fileName + extension
                }
            }
            // Sanitize file name to avoid invalid characters
            fileName = fileName.replace("[^a-zA-Z0-9._-]".toRegex(), "_")

            // Log for debugging
            println("Download File: $fileName, ContentDisposition: $contentDisposition, SuggestedFilename: $suggestedFilename, MimeType: $mimeType")

            // Set destination
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)

            // Set title
            request.setTitle(fileName)

            // Additional settings
            request.setAllowedOverMetered(true)
            request.setAllowedOverRoaming(false)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                request.setRequiresCharging(false)
                request.setRequiresDeviceIdle(false)
            }
            request.setVisibleInDownloadsUi(true)

            // Enqueue download
            val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
            downloadManager.enqueue(request)
            true
        } catch (e: Exception) {
            false
        }
    }
}
