package kr.co.vividnext.sodalive.extensions

import android.graphics.Typeface
import android.text.SpannableString
import kr.co.vividnext.sodalive.common.CustomTypefaceSpan
import java.text.SimpleDateFormat
import java.util.Locale

fun String.convertDateFormat(
    from: String,
    to: String,
    inputLocale: Locale = Locale.KOREAN,
    outputLocale: Locale = Locale.KOREAN
): String {
    val fromDateFormat = SimpleDateFormat(from, inputLocale)
    val toDateFormat = SimpleDateFormat(to, outputLocale)

    var outputDateString = ""
    val date = fromDateFormat.parse(this)

    if (date != null) {
        outputDateString = toDateFormat.format(date)
    }

    return outputDateString
}

fun String.fontSpan(typeface: Typeface?, text: String): SpannableString {
    val typefaceSpan = CustomTypefaceSpan(typeface)
    val spannableString = SpannableString(this)

    var startIndex = this.indexOf(text)

    while (startIndex != -1) {
        val endIndex = startIndex + text.length

        spannableString.setSpan(
            typefaceSpan,
            startIndex,
            endIndex,
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        startIndex = this.indexOf(text, endIndex)
    }

    return spannableString
}

fun String.prefix(length: Int): String {
    return if (this.length >= length) {
        this.substring(0, length)
    } else {
        this
    }
}
