package dev.fyloz.plannervio.core.service

import dev.fyloz.plannervio.core.model.BackgroundImage
import javafx.scene.image.Image
import mu.KotlinLogging
import java.io.FileInputStream
import java.io.InputStream

class BackgroundImageService : IBackgroundImageService {
    private val logger = KotlinLogging.logger { }

    override fun loadImage(image: BackgroundImage): Image? {
        val stream = getImageInputStream(image)
        return if (stream != null)
            Image(stream)
        else {
            logger.warn("Could not load image '${image.path}'")
            null
        }
    }

    /**
     * Gets the input stream for a given background image.
     *
     * @param image The background image
     */
    fun getImageInputStream(image: BackgroundImage): InputStream? {
        return if (image.bundled) {
            getBundledImageInputStream(image)
        } else {
            getCustomImageInputStream(image)
        }
    }

    /**
     * Gets the input stream for a given bundled background image.
     *
     * @param image The background image
     */
    fun getBundledImageInputStream(image: BackgroundImage): InputStream? {
        return ClassLoader.getSystemResourceAsStream("images/${image.path}")
    }

    /**
     * Gets the input stream for a given custom background image.
     *
     * @param image The background image
     */
    fun getCustomImageInputStream(image: BackgroundImage): InputStream? {
        return FileInputStream(image.path)
    }
}
