package ru.forbion.f7cloud.feature.contacts

object ContactRecipientHelper {
    fun formatRecipient(displayName: String, email: String): String {
        val name = displayName.trim()
        val mail = email.trim()
        if (mail.isBlank()) return name
        if (name.isBlank() || name.equals(mail, ignoreCase = true)) return mail
        return "$name <$mail>"
    }

    fun currentToken(raw: String): String {
        val tail = raw.substringAfterLast(',', raw).substringAfterLast(';', raw)
        return tail.trim()
    }

    fun replaceCurrentToken(raw: String, replacement: String): String {
        val comma = raw.lastIndexOf(',')
        val semicolon = raw.lastIndexOf(';')
        val sepIndex = maxOf(comma, semicolon)
        if (sepIndex < 0) return replacement
        val prefix = raw.substring(0, sepIndex + 1)
        return if (prefix.endsWith(' ')) {
            "$prefix$replacement"
        } else {
            "$prefix $replacement"
        }
    }
}
