package com.yidianling.common.binding

import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.view.View
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import com.ydl.ydl_image.module.GlideApp

@BindingAdapter("imageUrl", "circle", requireAll = false)
fun setImageUrl(imageView: ImageView, url: String?, circle: Boolean = false) {
    if (url.isNullOrEmpty()) return
    if (circle) {
        GlideApp.with(imageView).load(url).circleCrop().into(imageView)
    } else {
        GlideApp.with(imageView).load(url).into(imageView)
    }
}


@BindingAdapter(
    value = [
        "shapeBg",
        "shapeStrokeColor",
        "shapeStrokeWidth",
        "shapeRadius",
        "shape"
    ],
    requireAll = false
)
fun View.setCustomStyle(
    shapeBg: Int = Color.TRANSPARENT,                  // 背景颜色
    shapeStrokeColor: Int = Color.TRANSPARENT,                 // 边框颜色
    shapeStrokeWidth: Float = 0f,                              // 边框宽度
    shapeRadius: Float = 0f,                                    // 圆角宽度
    shape: Int = GradientDrawable.RECTANGLE               // Shape样式 默认矩形
) {
    val gradientDrawable: GradientDrawable = if (background as? GradientDrawable == null) {
        GradientDrawable()
    } else {
        background as GradientDrawable
    }
    val density = resources.displayMetrics.density
    gradientDrawable.setColor(shapeBg)
    gradientDrawable.setStroke(
        (shapeStrokeWidth * density).toInt(),
        shapeStrokeColor
    )
    val radius = density * shapeRadius
    gradientDrawable.cornerRadius = radius
    when (shape) {
        GradientDrawable.RECTANGLE -> gradientDrawable.shape = GradientDrawable.RECTANGLE
        GradientDrawable.OVAL -> gradientDrawable.shape = GradientDrawable.OVAL
        GradientDrawable.LINE -> gradientDrawable.shape = GradientDrawable.LINE
        GradientDrawable.RING -> gradientDrawable.shape = GradientDrawable.RING
        else -> gradientDrawable.shape = GradientDrawable.RECTANGLE
    }
    background = gradientDrawable
}