package com.adealink.weparty.webview.util

import android.net.Uri
import android.webkit.MimeTypeMap
import com.adealink.frame.ext.runSafely
import okhttp3.Headers
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import java.nio.charset.Charset


fun getCharsetFromHeaders(
    headers: Headers,
    default: String = Charset.defaultCharset().name()
): String = runSafely(default) {
    val contentType = headers["Content-Type"] ?: return@runSafely default
    val mediaType = contentType.toMediaTypeOrNull() ?: return@runSafely default
    return@runSafely mediaType.charset()?.toString() ?: default
}

@Suppress("RemoveExplicitTypeArguments")
fun getMimeTypeFromHeader(headers: Headers?) = runSafely<String?>(null) {
    val contentType = headers?.get("Content-Type") ?: return@runSafely null
    val mediaType = contentType.toMediaTypeOrNull() ?: return@runSafely null
    return@runSafely "${mediaType.type}/${mediaType.subtype}"
}

fun getMimeTypeFromUrl(_url: String, default: String = "text/html"): String {
    // 强行适配前端2倍图命名，png文件带@
    val url = _url.replace("@", "_")
    var mimeType: String? = null
    runSafely {
        val fileExtension = MimeTypeMap.getFileExtensionFromUrl(url)
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension)
    }
    if (mimeType == null) {
        mimeType = guessMimeFromUrl(url, default)
    }
    return mimeType!!
}

private fun guessMimeFromUrl(url: String, default: String): String = runSafely(default) {
    var mime = default
    val currentUri = Uri.parse(url)
    val path = currentUri.path
    path?.let {
        if (it.endsWith(".css")) {
            mime = "text/css"
        } else if (it.endsWith(".js")) {
            mime = "application/javascript"
        } else if (it.endsWith(".jpg") || it.endsWith(".gif") ||
            it.endsWith(".png") || it.endsWith(".jpeg") ||
            it.endsWith(".webp") || it.endsWith(".bmp") ||
            it.endsWith(".ico")
        ) {
            mime = "image/*"
        } else if (it.endsWith(".json")) {
            mime = "application/json"
        }
    }
    return mime
}