// SPDX-FileCopyrightText: 2023 CELESTIFYX Team
// SPDX-License-Identifier: GPL-3.0-or-later

use anyhow::Result;
use image::DynamicImage;

use super::{
    config::DisplayConfig,

    backend::{
        ImageBackend,
        get_best_backend
    }
};

pub struct ImageDisplay {
    backend: Option<Box<dyn ImageBackend>>,
    config: DisplayConfig
}

impl ImageDisplay {
    pub fn new(backend: Box<dyn ImageBackend>, config: DisplayConfig) -> Self {
        Self {
            backend: Some(backend),
            config
        }
    }

    pub fn auto() -> Result<Self> {
        Ok(Self {
            backend: get_best_backend()?,
            config: DisplayConfig::default()
        })
    }

    pub fn auto_with_config(config: DisplayConfig) -> Result<Self> {
        Ok(Self {
            backend: get_best_backend()?,
            config
        })
    }

    pub fn render(&self, image: &DynamicImage) -> Result<String> {
        let backend: &Box<dyn ImageBackend> = match &self.backend {
            Some(b) => b,
            None => anyhow::bail!("No image backend available")
        };

        backend.add_image(&self.config, image)
    }
}
