use std::io::{stdout, Write};
use terminal_size::{terminal_size, Width};
pub struct BarConf {
pub color: String,
pub chars: [char; 5]
}
pub fn str_to_color(color_str: &str) -> String{
match color_str.to_lowercase().as_str() {
"black" => String::from("\x1b[30m"),
"red" => String::from("\x1b[31m"),
"green" => String::from("\x1b[32m"),
"yellow" => String::from("\x1b[33m"),
"blue" => String::from("\x1b[34m"),
"magenta" => String::from("\x1b[35m"),
"cyan" => String::from("\x1b[36m"),
"white" => String::from("\x1b[37m"),
_ => String::from("\x1b[39m")
}
}
pub fn draw_bar(percent: u8, message: &str, message_before: bool, bar_config: BarConf) {
print!("\r{}", bar_config.color);
if let Some((Width(w), _h)) = terminal_size() {
let term_width = w as u16 - 11 - String::from(message).len() as u16;
let scale = term_width as f32/100.0;
let bar_length = (percent as f32 * scale) as u16;
if message_before == true {
print!("{} ", message);
}
print!("{}", bar_config.chars[0]);
for _i in 0..term_width {
if _i < (bar_length + 1) || (bar_length == (99.0 * scale) as u16) {
print!("{}", bar_config.chars[1]);
} else if _i == (bar_length + 1) {
print!("{}", bar_config.chars[2]);
} else {
print!("{}", bar_config.chars[3]);
}
}
}
print!("{} {}%", bar_config.chars[4], percent + 1);
if message_before == false {
print!(" {}", message);
}
print!("\x1b[39m");
stdout().flush().expect("Could not flush stdout");
}