package com.img.rabbit.utils

import android.content.Context
import android.widget.ImageView
import coil3.load
import coil3.request.crossfade
import coil3.request.transformations
import coil3.transform.RoundedCornersTransformation
import com.luck.picture.lib.engine.ImageEngine
import com.luck.picture.lib.utils.ActivityCompatHelper

class CoilEngine : ImageEngine {

    // 加载普通图片
    override fun loadImage(context: Context, url: String, imageView: ImageView) {
        if (!ActivityCompatHelper.assertValidRequest(context)) return
        imageView.load(url)
    }

    override fun loadImage(
        context: Context?,
        imageView: ImageView?,
        url: String?,
        maxWidth: Int,
        maxHeight: Int
    ) {
        if (!ActivityCompatHelper.assertValidRequest(context)) return
        imageView?.load(url)
    }

    // 加载相册目录封面
    override fun loadAlbumCover(context: Context, url: String, imageView: ImageView) {
        if (!ActivityCompatHelper.assertValidRequest(context)) return
        imageView.load(url) {
            transformations(RoundedCornersTransformation(8f))
            size(180, 180) // 优化内存，封面图没必要太大
        }
    }

    // 加载图片列表中的小图
    override fun loadGridImage(context: Context, url: String, imageView: ImageView) {
        if (!ActivityCompatHelper.assertValidRequest(context)) return
        imageView.load(url) {
            size(200, 200)
            crossfade(true)
        }
    }

    // 暂停/恢复加载（Coil 自动处理，可留空）
    override fun pauseRequests(context: Context?) {}
    override fun resumeRequests(context: Context?) {}

    companion object {
        private var instance: CoilEngine? = null
        fun createCoilEngine(): CoilEngine {
            return instance ?: synchronized(this) {
                instance ?: CoilEngine().also { instance = it }
            }
        }
    }
}
