package bou.amine.apps.readerforselfossv2.android.utils.glide

import android.content.Context
import android.graphics.Bitmap
import android.widget.ImageView
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.BitmapImageViewTarget
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream

fun Context.bitmapCenterCrop(url: String, iv: ImageView) =
    Glide.with(this)
        .asBitmap()
        .load(url)
        .apply(RequestOptions.centerCropTransform())
        .into(iv)

fun Context.circularBitmapDrawable(url: String, iv: ImageView) =
    Glide.with(this)
        .asBitmap()
        .load(url)
        .apply(RequestOptions.centerCropTransform())
        .into(object : BitmapImageViewTarget(iv) {
            override fun setResource(resource: Bitmap?) {
                val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(
                    resources,
                    resource
                )
                circularBitmapDrawable.isCircular = true
                iv.setImageDrawable(circularBitmapDrawable)
            }
        })

fun getBitmapInputStream(bitmap:Bitmap,compressFormat: Bitmap.CompressFormat): InputStream {
    val byteArrayOutputStream = ByteArrayOutputStream()
    bitmap.compress(compressFormat, 80, byteArrayOutputStream)
    val bitmapData: ByteArray = byteArrayOutputStream.toByteArray()
    return ByteArrayInputStream(bitmapData)
}