package it.danieleverducci.openweddingapp.utils

import android.os.Build
import android.widget.TextView
import androidx.core.graphics.drawable.DrawableCompat
import it.danieleverducci.openweddingapp.entities.User
import java.text.Normalizer
import java.util.Locale
import java.util.Locale.getDefault

object ViewUtils {
    fun colorizeUserBadge(badge: TextView, user: User) {
        val bgDrawable = DrawableCompat.wrap(badge.getBackground())
        if (Build.VERSION.SDK_INT >= 21)
            bgDrawable.setTint(user.badgeColor)
    }

    /**
     * Returns a color component (0-255) from the provided string
     */
    fun getUserBadgeColorComponentFromString(string: String, channel: Int): Int {
        if (string.length - 1 < channel)
            return 0

        // Remove accents and strange symbols and toUppercase
        val normStr = Normalizer.normalize(string.uppercase(getDefault()), Normalizer.Form.NFD)
            .replace("\\p{Mn}+".toRegex(), "")

        // Get desired channel int from string
        var channel = normStr.get(channel).toInt()

        // Remap ascii values A-Z (65-90) to 0-255
        if (channel < 65)
            channel = 0
        else if (channel > 90)
            channel = 255
        else
            channel = ((channel - 65).toFloat() / 25 * 255).toInt()

        // Be sure the value is between 0 and 255
        return Math.max(Math.min(channel, 255), 0)
    }
}