package com.abbidot.tracker.util

import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.widget.ImageView
import coil.ImageLoader
import coil.load
import coil.request.ImageRequest
import com.huantansheng.easyphotos.engine.ImageEngine

/**
 * 相册拍照显示图片封装
 */
class CoilEngine private constructor() : ImageEngine {

    companion object {
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { CoilEngine() }
    }

    private fun ImageView.loadImage(
            uri: Uri,
            imageLoader: ImageLoader = context.imageLoader(),
            builder: ImageRequest.Builder.() -> Unit = {},
    ) {
//        if (SDK_INT >= Build.VERSION_CODES.Q) {
//            if (uri.startsWith("content://")) {
//                load(Uri.parse(uri), imageLoader, builder)
//            } else {
//                load(uri, imageLoader, builder)
//            }
//        } else {
//            load(File(uri), imageLoader, builder)
//        }
        load(uri, imageLoader, builder)
    }

    private fun Context.imageLoader(): ImageLoader {
        return ImageLoader.Builder(this).componentRegistry {
//                add(VideoFrameFileFetcher(this@imageLoader))
//                add(VideoFrameUriFetcher(this@imageLoader))
//                add(VideoFrameDecoder(this@imageLoader))
        }.build()
    }


    override fun loadPhoto(context: Context, uri: Uri, imageView: ImageView) {
        imageView.loadImage(uri)
    }

    override fun loadGifAsBitmap(context: Context, gifUri: Uri, imageView: ImageView) {
        imageView.loadImage(gifUri)
    }

    override fun loadGif(context: Context, gifUri: Uri, imageView: ImageView) {
        imageView.loadImage(gifUri)
    }

    override fun getCacheBitmap(context: Context, uri: Uri, width: Int, height: Int): Bitmap? {
        return null
    }
}
