package cy.hexor.furumi.data.repository

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import java.io.File
import java.io.IOException
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request

@Singleton
class MediaImageLoader @Inject constructor(
    private val okHttpClient: OkHttpClient
) {
    suspend fun load(url: String): Result<Bitmap> {
        return withContext(Dispatchers.IO) {
            runCatching {
                if (url.startsWith("file://", ignoreCase = true)) {
                    val path = Uri.parse(url).path ?: throw IOException("Image file path is empty")
                    return@runCatching BitmapFactory.decodeFile(path)
                        ?: throw IOException("Image file is not a supported bitmap")
                }

                if (url.startsWith("/", ignoreCase = false)) {
                    return@runCatching BitmapFactory.decodeFile(File(url).absolutePath)
                        ?: throw IOException("Image file is not a supported bitmap")
                }

                val request = Request.Builder()
                    .url(url)
                    .build()

                okHttpClient.newCall(request).execute().use { response ->
                    if (!response.isSuccessful) {
                        throw IOException("Image request failed with HTTP ${response.code}")
                    }

                    val bytes = response.body?.bytes()
                        ?: throw IOException("Image response is empty")

                    BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
                        ?: throw IOException("Image response is not a supported bitmap")
                }
            }
        }
    }
}
