package cz.softdeluxe.jlib


import java.security.SecureRandom
import java.text.Normalizer
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.*
import java.util.concurrent.ThreadLocalRandom
import java.util.regex.Pattern

inline val random: ThreadLocalRandom get() = ThreadLocalRandom.current()

private val secureRandom = SecureRandom()

fun randomString(length: Int): String {
    val uuid = UUID.randomUUID().toString().replace("-", "")
    return if (length < uuid.length) uuid.substring(0, length) else uuid
}

fun randomLocalDate(maxYear: Int = 2100): LocalDate {
    return LocalDate.of(random.nextInt(0, maxYear), random.nextInt(1, 12), random.nextInt(1, 29))
}

fun randomLocalDateTime(maxYear: Int = 2100): LocalDateTime {
    return randomLocalDate().atStartOfDay()
}

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

fun String.removeDiakritiku(): String {
    val normalize = Normalizer.normalize(this, Normalizer.Form.NFD)
    return normalize.filter { it <= '\u007F' }
}

val regexpNonNumeric = Regex("[^\\p{L}\\p{Nd}]+")
fun String.removeNonAlphaNorNumeric(): String {
    return this.replace(regexpNonNumeric, "")
}

val regexpNotAlowedInFileName = Regex("[^a-zA-Z0-9.-]")
fun String.removeNotAlowedInFileName(): String {
    return this.replace(regexpNotAlowedInFileName, "")
}

fun String?.emptyToNull(): String? = if (this.isNullOrEmpty()) null else this
fun String?.blankToNull(): String? = if (this.isNullOrBlank()) null else this

fun String.isInteger(): Boolean = toIntOrNull() != null

private val emailmPattern = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+")
fun parseEmail(str: String):Sequence<String> {
    val matcher = emailmPattern.matcher(str)

    return generateSequence {
        if(matcher.find()) matcher.group() else null
    }
}