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

use anyhow::Result;
use image::DynamicImage;
use clap::ValueEnum;

use serde::{
    Serialize,
    Deserialize
};

use iterm::ITermBackend;
use kitty::KittyBackend;
use sixel::SixelBackend;

use super::config::DisplayConfig;

mod iterm;
mod kitty;
mod sixel;

pub trait ImageBackend {
    fn add_image(&self, config: &DisplayConfig, image: &DynamicImage) -> Result<String>;
}

#[derive(ValueEnum, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum ImageProtocol {
    Kitty,
    Sixel,
    Iterm
}

pub fn get_best_backend() -> Result<Option<Box<dyn ImageBackend>>> {
    if SixelBackend::supported()? {
        Ok(Some(Box::new(SixelBackend)))
    } else if KittyBackend::supported()? {
        Ok(Some(Box::new(KittyBackend)))
    } else if ITermBackend::supported() {
        Ok(Some(Box::new(ITermBackend)))
    } else {
        Ok(None)
    }
}

pub fn get_image_backend(image_protocol: ImageProtocol) -> Option<Box<dyn ImageBackend>> {
    let backend: Option<Box<dyn ImageBackend>> = Some(match image_protocol {
        ImageProtocol::Kitty => Box::new(KittyBackend) as Box<dyn ImageBackend>,
        ImageProtocol::Iterm => Box::new(ITermBackend) as Box<dyn ImageBackend>,
        ImageProtocol::Sixel => Box::new(SixelBackend) as Box<dyn ImageBackend>
    });

    backend
}
