use std::io;
use std::io::Write;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use crate::utils::Color;
pub struct LoadingIndicator {
is_running: Arc<Mutex<bool>>,
color: Color,
}
impl Default for LoadingIndicator {
fn default() -> Self {
Self {
is_running: Arc::new(Mutex::new(false)),
color: Color::White,
}
}
}
impl LoadingIndicator {
pub fn new(color: Color) -> Self {
Self {
is_running: Arc::new(Mutex::new(false)),
color,
}
}
pub fn start(&self) {
let is_running = self.is_running.clone();
*is_running.lock().unwrap() = true;
let color_code = self.color.to_ansi_code();
thread::spawn(move || {
let spinner_chars = vec!['|', '/', '-', '\\'];
let mut index = 0;
println!("{}", color_code); while *is_running.lock().unwrap() {
print!("\r{}", spinner_chars[index]);
io::stdout().flush().unwrap();
index = (index + 1) % spinner_chars.len();
thread::sleep(Duration::from_millis(100));
}
println!();
io::stdout().flush().unwrap();
});
}
pub fn stop(&self) {
*self.is_running.lock().unwrap() = false;
}
}