package com.pixelized.biblib.utils.extention

import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import java.util.*

fun String.capitalize() = this.replaceFirstChar {
    if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString()
}

@Composable
fun stringRegex(
    annotatedText: String
) = remember(annotatedText) {
    Regex(annotatedText)
}

@Composable
fun String.highlight(
    highlight: Regex,
    defaultStyle: SpanStyle = MaterialTheme.typography.body1.toSpanStyle(),
    strongStyle: SpanStyle = defaultStyle.copy(fontWeight = FontWeight.Bold),
): AnnotatedString = remember(this, highlight, defaultStyle, strongStyle) {
    buildAnnotatedString {
        withStyle(defaultStyle) {
            append(this@highlight)
        }
        highlight.find(this@highlight)?.let { result ->
            addStyle(
                style = strongStyle,
                start = result.range.first,
                end = result.range.last + 1,
            )
        }
    }
}