package com.common.commonlib.image.loader

import android.graphics.drawable.Drawable
import com.bumptech.glide.RequestBuilder
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.common.commonlib.image.config.GlideHolderConfig

/**
 * 全局配置适配器
 *
 * @author wangym
 * @since 2021/7/28
 */
object GlobalConfigHelper {
    /**
     * 全局占位符配置
     */
    var globalHolderConfig: GlideHolderConfig? = null

    /**
     * 全局过渡效果
     */
    var globalTransition: DrawableTransitionOptions? = null

    fun loadWithGlobalConfig(requestBuilder: RequestBuilder<Drawable>): RequestBuilder<Drawable> {
        return loadWithGlobalConfig(requestBuilder, globalHolderConfig, globalTransition)
    }

    fun loadWithGlobalConfig(
        requestBuilder: RequestBuilder<Drawable>,
        holderConfig: GlideHolderConfig?
    ): RequestBuilder<Drawable> {
        return loadWithGlobalConfig(requestBuilder, holderConfig, globalTransition)
    }

    private fun loadWithGlobalConfig(
        requestBuilder: RequestBuilder<Drawable>,
        holderConfig: GlideHolderConfig?,
        transition: DrawableTransitionOptions?
    ): RequestBuilder<Drawable> {
        var request = requestBuilder
        if (holderConfig != null) {
            if (holderConfig.holderDrawable != null) {
                request = request.placeholder(holderConfig.holderDrawable)
            }
            if (holderConfig.holderId != -1) {
                request = request.placeholder(holderConfig.holderId)
            }
            if (holderConfig.errorDrawable != null) {
                request = request.error(holderConfig.errorDrawable)
            }
            if (holderConfig.errorId != -1) {
                request = request.error(holderConfig.errorId)
            }
            if (holderConfig.errorBuilder != null) {
                request = request.error(holderConfig.errorBuilder)
            }
            if (holderConfig.fallBackDrawable != null) {
                request = request.fallback(holderConfig.fallBackDrawable)
            }
            if (holderConfig.fallBackId != -1) {
                request = request.fallback(holderConfig.fallBackId)
            }
        }

        if (transition != null) {
            request = request.transition(transition)
        }
        return request
    }
}