package cn.muchinfo.rma.view.autoWidget

import android.app.Activity
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions


fun <IMAGE : ImageView?> IMAGE.showImage(imageUrl: String?, block: ((RequestOptions) -> RequestOptions)? = null) {
    if (isEnableToLoad(this).not()) {
        return
    }
    val defaultOptions = RequestOptions()
            .centerCrop()
            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
    (this as ImageView).loadImage(imageUrl, block?.invoke(defaultOptions) ?: defaultOptions)
}

fun <IMAGE : ImageView?> IMAGE.showRoundImage(imageUrl: String?, block: ((RequestOptions) -> RequestOptions)? = null) {
    if (isEnableToLoad(this).not()) {
        return
    }
    val defaultOptions = RequestOptions()
            .centerCrop()
            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
            .circleCrop()
    (this as ImageView).loadImage(imageUrl, block?.invoke(defaultOptions) ?: defaultOptions)
}

fun <IMAGE : ImageView> IMAGE.showImage(imageResource: Int, block: ((RequestOptions) -> RequestOptions)? = null) {
    if (isEnableToLoad(this).not()) {
        return
    }
    val defaultOptions = RequestOptions()
            .centerCrop()
            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
    Glide.with(context)
            .load(imageResource)
            .apply(block?.invoke(defaultOptions) ?: defaultOptions)
            .into(this as ImageView)
}

internal fun <IMAGE : ImageView?> isEnableToLoad(view: IMAGE): Boolean {
    return (view != null).and((view?.context as? Activity)?.isDestroyed?.not() == true)
}

internal fun <IMAGE : ImageView> IMAGE.loadImage(imageUrl: String?, requestOptions: RequestOptions) {
    Glide.with(context)
            .load(imageUrl)
            .apply(requestOptions)
            .into(this as ImageView)
}