package net.buzzert.kordophonedroid.ui.shared

import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextDecoration

const val LINK_ANNOTATION_TAG = "link"
private val LINK_REGEX = "(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]".toRegex()

fun String.linkify(): AnnotatedString {
    val text = this
    val matches = LINK_REGEX.findAll(this)
    return buildAnnotatedString {
        append(text)

        for (match in matches) {
            val range = match.range.also {
                // Make inclusive.
                IntRange(it.first, it.last + 1)
            }

            // Annotate link
            addStringAnnotation(LINK_ANNOTATION_TAG, match.value, range.first, range.last)

            // Add style
            addStyle(
                style = SpanStyle(textDecoration = TextDecoration.Underline),
                start = range.first, end = range.last
            )
        }
    }
}