use colored::Colorize;
use rtodo::commands::execute_commands;
use std::process::Command;
use std::sync::{atomic::{AtomicBool, Ordering},Arc};
use rtodo::persistence;
use rtodo::todos::Todo;
use rtodo::{
add_todo, main_menu, remove_todo, save_and_exit, show_todos, sub_menu, update_todo, user_input,
};
fn main() {
let running = Arc::new(AtomicBool::new(true));
let first_catch = running.clone();
let last_catch = running.clone();
ctrlc::set_handler(move || {
first_catch.store(false, Ordering::SeqCst);
})
.expect("Error creating a handler!!!");
let mut todos: Vec<Todo> = vec![];
if let Ok(vec) = persistence::read_from_file() {
todos.extend(vec);
}
if let Err(e) = execute_commands(&mut todos) {
println!("Error execute the command!!! {e}");
}
loop {
while running.load(Ordering::SeqCst) {
Command::new("clear").status().unwrap();
main_menu();
print!(
"{}{}",
"Choose an option ".white().bold(),
"-> ".green().bold()
);
let user = match user_input() {
Ok(u) => u.trim().to_string(),
Err(e) => panic!("Error get user input {e}"),
};
if user.contains('1') {
show_todos(&mut todos);
while let Ok(e) = sub_menu(&mut todos) {
if !e {
break;
}
show_todos(&mut todos);
}
} else if user.contains('2') {
if let Err(e) = add_todo(&mut todos) {
println!("Error add todo!!! {e}");
}
} else if user.contains('3') {
show_todos(&mut todos);
if let Err(e) = update_todo(&mut todos) {
println!("Error update todo!!! {e}");
}
} else if user.contains('4') {
show_todos(&mut todos);
if let Err(e) = remove_todo(&mut todos) {
println!("Error remove todo!!! {e}");
}
} else if user.contains('5') {
if let Err(e) = persistence::write_to_file(&todos) {
println!("Error save to file!!! {e}");
}
std::process::exit(0);
}
}
print!(
"{}{}{}",
"Do you want exit?".red().bold(),
" [Y/N]".yellow().bold(),
" -> ".green().bold()
);
if let Ok(confirm) = user_input() {
if confirm.trim().eq_ignore_ascii_case("y") {
save_and_exit(&mut todos);
} else {
last_catch.store(true, Ordering::SeqCst);
}
}
} }