package ru.forbion.f7cloud.feature.talk

/** Parses Talk/spreed deep links from push and web URLs. */
object TalkDeepLink {
    fun extractRoomToken(url: String?): String? {
        if (url.isNullOrBlank()) return null
        val callMarker = "/call/"
        val callIdx = url.indexOf(callMarker)
        if (callIdx >= 0) {
            val rest = url.substring(callIdx + callMarker.length)
            return rest.takeWhile { it.isLetterOrDigit() }.ifBlank { null }
        }
        val spreedMarker = "/apps/spreed/"
        val spreedIdx = url.indexOf(spreedMarker)
        if (spreedIdx >= 0) {
            val rest = url.substring(spreedIdx + spreedMarker.length)
            val token = rest.substringBefore('/').substringBefore('?').substringBefore('#')
            if (token.isNotBlank() && token != "api") return token
        }
        return null
    }

    fun extractMessageId(url: String?): Long? {
        if (url.isNullOrBlank()) return null
        val fragMarker = "#message_"
        val idx = url.indexOf(fragMarker)
        if (idx >= 0) {
            return url.substring(idx + fragMarker.length).takeWhile { it.isDigit() }.toLongOrNull()
        }
        return null
    }
}
