use crate::schema::{ConfigItem, ConfigType};
use anyhow::Result;
use std::collections::HashMap;
use std::fmt::Write;

pub fn generate(items: &[ConfigItem], values: &HashMap<String, toml::Value>) -> Result<String> {
    let mut buffer = String::new();

    writeln!(buffer, "/* Generated by anaxa-config */")?;
    writeln!(buffer, "#ifndef _AUTOCONF_H_")?;
    writeln!(buffer, "#define _AUTOCONF_H_")?;
    writeln!(buffer)?;

    for item in items {
        if let Some(val) = values.get(&item.name) {
            write_item_define(&mut buffer, item, val)?;
        }
    }

    writeln!(buffer)?;
    writeln!(buffer, "#endif /* _AUTOCONF_H_ */")?;

    Ok(buffer)
}

fn write_item_define(buffer: &mut String, item: &ConfigItem, val: &toml::Value) -> Result<()> {
    let name = format!("CONFIG_{}", item.name);

    if item.config_type == ConfigType::Bool && val.as_bool() == Some(false) {
        writeln!(buffer, "/* {} is not set */", name)?;
    } else if let Some(formatted) = item.config_type.format_value_c(val) {
        writeln!(buffer, "#define {} {}", name, formatted)?;
    }
    Ok(())
}
