package com.adealink.weparty.util

import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Shader
import com.adealink.frame.image.imageService
import com.adealink.frame.image.listener.IImageLoadResultListener
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

object ImageUtil {
    @JvmStatic
    fun createCircularBitmapWithBorder(
        bitmap: Bitmap,
        borderWidthPx: Int,
        borderColor: Int
    ): Bitmap? {
        if (bitmap.isRecycled) {
            return null
        }

        val width: Int = bitmap.width + borderWidthPx
        val height: Int = bitmap.height + borderWidthPx
        val canvasBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val shader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
        val paint = Paint()
        paint.isAntiAlias = true
        paint.shader = shader
        val canvas = Canvas(canvasBitmap)
        val radius = if (width > height) height.toFloat() / 2f else width.toFloat() / 2f
        canvas.drawCircle((width / 2).toFloat(), (height / 2).toFloat(), radius, paint)
        paint.shader = null
        paint.style = Paint.Style.STROKE
        paint.color = borderColor
        paint.strokeWidth = borderWidthPx.toFloat()
        canvas.drawCircle(
            (width / 2).toFloat(),
            (height / 2).toFloat(),
            radius - borderWidthPx / 2,
            paint
        )
        return canvasBitmap
    }
}

suspend fun fetchImage(url: String?): Bitmap? {
    if (url.isNullOrEmpty()) {
        return null
    }
    return suspendCancellableCoroutine { continuation ->
        imageService.fetchImage(url, object : IImageLoadResultListener {
            override fun onSuccess(bitmap: Bitmap) {
                super.onSuccess(bitmap)
                if (continuation.isActive) {
                    continuation.resume(bitmap)
                }
            }

            override fun onFailed() {
                super.onFailed()
                continuation.resume(null)
            }
        })
    }
}