package de.storchp.fdroidbuildstatus.utils

import android.content.Context
import android.graphics.drawable.Drawable
import android.view.Menu
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat

object DrawableUtils {
    fun setMenuIconTint(context: Context?, menu: Menu, itemId: Int, color: Int) {
        var drawable = menu.findItem(itemId).icon
        drawable = DrawableCompat.wrap(drawable!!)
        DrawableCompat.setTint(drawable, ContextCompat.getColor(context!!, color))
        menu.findItem(itemId).icon = drawable
    }

    fun setIconWithTint(context: Context?, imageView: ImageView, imageId: Int, color: Int) {
        imageView.setImageDrawable(getTintedDrawable(context, imageId, color))
    }

    fun setCompoundDrawablesLeft(textView: TextView, image: Drawable?, color: Int) {
        textView.setCompoundDrawablesWithIntrinsicBounds(
            getTintedDrawable(image, color),
            null,
            null,
            null
        )
    }

    fun setCompoundDrawablesRight(context: Context?, textView: TextView, imageId: Int, color: Int) {
        textView.setCompoundDrawablesWithIntrinsicBounds(
            null,
            null,
            getTintedDrawable(context, imageId, color),
            null
        )
    }

    fun getTintedDrawable(context: Context?, imageId: Int, color: Int): Drawable? {
        if (imageId > 0) {
            val unwrappedDrawable = ContextCompat.getDrawable(context!!, imageId)
            return getTintedDrawable(unwrappedDrawable, color)
        }
        return null
    }

    private fun getTintedDrawable(unwrappedDrawable: Drawable?, color: Int): Drawable? {
        if (unwrappedDrawable != null) {
            val wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable)
            DrawableCompat.setTint(wrappedDrawable, color)
            return wrappedDrawable
        }
        return null
    }
}