use colored::*;
use log::{info, Level};
use reef::Command;
use std::collections::HashMap;

use fern::Dispatch;
use log::LevelFilter;

fn main() {
    // initialize logging
    init(Level::Info, HashMap::new()).unwrap();

    info!("{}", "");
    info!("{}{}", "executing a few commands".yellow(), "...".clear());
    Command::new("git --version").exec().unwrap();

    //let mut commands = Commands::new();
    // git --version
    //info!("{}", commands.exec("git --version"));
    //info!("{}", commands.exec("git --bad"));
    //info!("{}", commands.exec("foo"));
}

pub fn init(
    level: Level,
    target_level_filters: HashMap<String, LevelFilter>,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
    let level_filter = match level {
        Level::Debug => LevelFilter::Debug,
        _ => LevelFilter::Info,
    };

    let mut dispatch = Dispatch::new()
        .format(move |out, message, record| {
            match level {
                Level::Debug => out.finish(format_args!(
                    "{:>5} [{}] {}",
                    record.level(),
                    record.target(),
                    message
                )),
                _ => out.finish(format_args!("{}", message)),
            };
        })
        .level(level_filter)
        .chain(std::io::stdout());

    for (key, value) in target_level_filters.into_iter() {
        dispatch = dispatch.level_for(key, value);
    }

    dispatch.apply()?;
    Ok(())
}
