package com.pixelized.desktop.lwa.repository.resources

import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.toComposeImageBitmap
import com.pixelized.desktop.lwa.ui.composable.image.ImagerModelConverter
import io.ktor.client.HttpClient
import io.ktor.client.request.get
import io.ktor.client.statement.readRawBytes
import org.jetbrains.skia.Image

class ImageResourcesRepository(
    private val httpClient: HttpClient,
    private val googleImageConverter: ImagerModelConverter,
) {
    suspend fun load(url: String): ImageBitmap {
        try {
            val unwrapUri = googleImageConverter.unwrap(model = url)
            val byteArray = httpClient.get(unwrapUri).readRawBytes()
            val skiaImage = Image.makeFromEncoded(byteArray)
            return skiaImage.toComposeImageBitmap()
        } catch (_: Exception) {
            // TODO proper exception handling (error bus ?)
            return ImageBitmap(width = 1, height = 1)
        }
    }
}