use tabled::{Table, Tabled};

use crate::{
    commands::Config, database::Result, entities::format_tag, jobber::JobberGet,
    views::ApplyTableStyle,
};

#[derive(Tabled)]
pub(crate) struct TagView {
    #[tabled(rename = "Tag")]
    pub(crate) name: String,
    #[tabled(rename = "Description")]
    pub(crate) description: String,
}

impl TagView {
    pub(crate) fn new(name: &str, database: &impl JobberGet, ansi: bool) -> Result<Self> {
        let tag = database.get_tag(name)?;
        Ok(Self {
            name: format_tag(name, tag, ansi),
            description: tag.description.clone().unwrap_or("-".to_string()),
        })
    }
}

impl std::fmt::Display for TagView {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "       Name: {}", self.name)?;
        writeln!(f, "Description: {}", self.description)
    }
}

pub(crate) fn create_tag_table(rows: impl IntoIterator<Item = TagView>, config: &Config) -> Table {
    let mut table = Table::new(rows);
    table.style(&config.table_style);
    table
}
