package ru.forbion.f7cloud.feature.files

import java.net.URI

object OfficeFileLinks {
    fun parseFileId(link: String, serverUrl: String): Long? {
        if (link.isBlank()) return null
        val base = serverUrl.trimEnd('/')
        val candidates = listOf(
            Regex("""${Regex.escape(base)}/index\.php/f/(\d+)""", RegexOption.IGNORE_CASE),
            Regex("""${Regex.escape(base)}/f/(\d+)""", RegexOption.IGNORE_CASE),
            Regex("""/index\.php/f/(\d+)""", RegexOption.IGNORE_CASE),
            Regex("""/f/(\d+)""", RegexOption.IGNORE_CASE),
        )
        for (pattern in candidates) {
            val match = pattern.find(link) ?: continue
            return match.groupValues[1].toLongOrNull()
        }
        return runCatching {
            val uri = URI(link)
            val path = uri.path.orEmpty()
            Regex("""/f/(\d+)""").find(path)?.groupValues?.get(1)?.toLongOrNull()
        }.getOrNull()
    }

    fun titleFromLink(link: String, fallback: String): String {
        return fallback.ifBlank {
            link.substringAfterLast('/').substringBefore('?').ifBlank { "Документ" }
        }
    }
}
