package com.ponzischeme89.memby.ui.player

import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.widget.ImageView
import androidx.core.graphics.drawable.toBitmap

/**
 * Applies a white treatment only to artwork whose visible pixels are overwhelmingly dark.
 * Transparent padding is ignored, so sparse black wordmarks are detected reliably without
 * flattening colourful or deliberately two-tone artwork.
 */
internal fun makeLogoVisibleOnDarkBackground(imageView: ImageView, drawable: Drawable): Boolean {
    imageView.setImageDrawable(drawable)
    imageView.clearColorFilter()
    val tintWhite = isPredominantlyDarkLogo(drawable)
    if (tintWhite) imageView.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN)
    return tintWhite
}

internal fun isPredominantlyDarkLogo(drawable: Drawable): Boolean {
    val bitmap = runCatching {
        drawable.toBitmap(width = 96, height = 64, config = Bitmap.Config.ARGB_8888)
    }.getOrNull() ?: return false
    val xStep = (bitmap.width / 48).coerceAtLeast(1)
    val yStep = (bitmap.height / 32).coerceAtLeast(1)
    var visible = 0
    var dark = 0
    var bright = 0
    for (y in 0 until bitmap.height step yStep) {
        for (x in 0 until bitmap.width step xStep) {
            val pixel = bitmap.getPixel(x, y)
            if (Color.alpha(pixel) < 32) continue
            visible++
            val luminance = (
                Color.red(pixel) * 0.2126f +
                    Color.green(pixel) * 0.7152f +
                    Color.blue(pixel) * 0.0722f
                ) / 255f
            if (luminance < 0.32f) dark++
            if (luminance > 0.72f) bright++
        }
    }
    return visible > 0 && dark * 100 >= visible * 68 && bright * 100 < visible * 12
}
