package ru.forbion.f7cloud.feature.files

import android.webkit.MimeTypeMap
import java.util.Locale

object ArchiveFiles {
    private val EXT = setOf(
        "zip", "rar", "7z", "tar", "gz", "tgz", "bz2", "tbz2", "tbz", "xz", "txz",
        "zst", "tzst", "lzma", "cab", "lz", "lzo",
    )

    fun isArchive(name: String): Boolean {
        val lower = name.lowercase(Locale.ROOT)
        val dot = lower.lastIndexOf('.')
        if (dot == -1) return false
        return lower.substring(dot + 1) in EXT
    }

    fun mimeType(name: String): String {
        val ext = name.lowercase(Locale.ROOT).substringAfterLast('.', missingDelimiterValue = "")
        MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext)?.let { return it }
        return when (ext) {
            "rar" -> "application/x-rar-compressed"
            "7z" -> "application/x-7z-compressed"
            "tar" -> "application/x-tar"
            "gz", "tgz" -> "application/gzip"
            "bz2", "tbz", "tbz2" -> "application/x-bzip2"
            "xz", "txz" -> "application/x-xz"
            "zip" -> "application/zip"
            else -> "application/octet-stream"
        }
    }
}
