package com.isidroid.utils

import java.security.MessageDigest
import java.text.DecimalFormat
import java.text.NumberFormat
import java.util.Locale
import kotlin.math.ln
import kotlin.math.log10
import kotlin.math.pow

val String.digitals get() = replace("[^0-9]".toRegex(), "")

val Long.withSuffix: String
    get() {
        if (this < 1000) return "" + this
        val exp = (ln(this.toDouble()) / ln(1000.0)).toInt()
        return String.format(
            "%.1f%c",
            this / 1000.0.pow(exp.toDouble()),
            "kMGTPE"[exp - 1]
        )
    }

val Int.withSuffix get() = toLong().withSuffix


val String.md5: String
    get() {
        val md = MessageDigest.getInstance("MD5")
        val digested = md.digest(toByteArray())
        return digested.joinToString("") { String.format("%02x", it) }
    }

val String.asFileName: String
    get() = take(20)
        .let { "\\s".toRegex().replace(it, "_") }
        .let { "[^a-zA-Z0-9 ]".toRegex().replace(it, "_") }
        .let { "_{2,}".toRegex().replace(it, "") }
        .lowercase()


val Long.asFileSize: String
    get() {
        if (this <= 0) return "0";
        val size = toDouble()

        val units = listOf("B", "KB", "MB", "GB", "TB")
        val digitGroups = log10(size) / log10(1024.0)

        return DecimalFormat("#,##0.#").format(size / 1024.0.pow(digitGroups)) + " " + units[digitGroups.toInt()]
    }

val String.capitalized get() = trim().lowercase().replaceFirstChar { it.uppercase() }

fun Float.asCost(lang: String? = null, country: String? = null): String {
    val locale = if (lang != null && country != null)
        Locale(lang, country)
    else
        Locale.getDefault()

    val currencyFormat = NumberFormat.getCurrencyInstance(locale)
    return currencyFormat.format(this)
}

fun String.spaceInCenter(): String {
    val mid = length / 2
    val left = substring(0, mid)
    val right = substring(mid, length)

    return buildString {
        append(left)
        append(" ")
        append(right)
    }
}