package com.rdiot.yx485.adapter

import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.rdiot.yx485.R
import com.rdiot.yx485.base.LocalData
import com.rdiot.yx485.util.circleImg
import com.rdiot.yx485.util.dp

/**
 *
 * @author mR2hao
 * @date 2022/11/14
 */
object CustomDataBindAdapter {
    @JvmStatic
    @BindingAdapter(value = ["srcString", "radiusDp"], requireAll = false)
    fun setImageResByString(img: ImageView, srcStr: String?, radius: Int) {
        if (!srcStr.isNullOrBlank()) {
            val id = img.context.resources.getIdentifier(srcStr, "mipmap", img.context.packageName)
            if (id >= 0) {
                if (radius == 0) {
                    img.setImageResource(id)
                } else {
                    Glide.with(img.context)
                        .load(id)
                        .apply(
                            RequestOptions().transform(CenterCrop(), RoundedCorners(radius.dp))
                        )
                        .into(img)
                }

            }
        }
    }


    @JvmStatic
    @BindingAdapter(value = ["circleImg"], requireAll = false)
    fun setCircleImage(img: ImageView, srcStr: String) {
        if (srcStr == "icon_member_add") {
            setImageResByString(img, srcStr, 0)
        } else {
            img.circleImg(LocalData.apiHost.avatarHost + srcStr)
        }
    }

    @JvmStatic
    @BindingAdapter(value = ["mode", "lv"], requireAll = true)
    fun setModeLevelText(tv: TextView, mode: Int, lv: Int) {
        val context = tv.context
        val modeStr = context.resources.getStringArray(R.array.modes)[mode]
        val lvStr = context.resources.getStringArray(R.array.fan_speed)[lv]
        tv.text = String.format(context.getString(R.string.mode_lv_str), modeStr, lvStr)
    }

}