package app.furmeet.events.brasilfurfest.helper

import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt

private val Int.monochrome
    get(): Int {
        val r = this.absoluteValue.and(0x00FF0000).shr(16)
        val g = this.absoluteValue.and(0x0000FF00).shr(8)
        val b = this.absoluteValue.and(0x000000FF)
        val mono = (0.2126 * r) + (0.7152 * g) + (0.0722 * b) // From: https://en.wikipedia.org/wiki/Relative_luminance
        return max(0, min(255, mono.roundToInt()))
    }

fun Int.decideBestForegroundColor(vararg colors: Int): Int {
    val monochrome = this.monochrome
    return colors.map { color ->
        color.monochrome.let { Triple(color, it, (monochrome - it).absoluteValue) }
    }.sortedBy {
        it.third
    }.last().first
}