#![allow(unused_imports)]
use log::{debug, error, info};
use std::{fs, path::PathBuf};
use crate::app::{AppError, Result, Task, TaskList};
const TASKS_FILE_NAME: &str = "tasks.toml";
fn get_tasks_file_path() -> PathBuf {
PathBuf::from(TASKS_FILE_NAME)
}
pub fn load_tasks() -> Result<Vec<Task>> {
let path = get_tasks_file_path();
debug!("Attempting to load tasks from: {}", path.display());
if !path.exists() {
info!(
"Tasks file not found at {}. Returning empty list.",
path.display()
);
return Ok(Vec::new());
}
let contents = fs::read_to_string(&path)?;
debug!("Successfully read contents from {}.", path.display());
let task_list: TaskList =
toml::from_str(&contents).map_err(|e| AppError::TomlDeserialize(e))?;
info!(
"Successfully loaded {} tasks from {}.",
task_list.tasks.len(),
path.display()
);
Ok(task_list.tasks)
}
pub fn save_tasks(tasks: &[Task]) -> Result<()> {
let path = get_tasks_file_path();
debug!(
"Attempting to save {} tasks to: {}",
tasks.len(),
path.display()
);
let task_list = TaskList {
tasks: tasks.to_vec(),
};
let contents = toml::to_string(&task_list).map_err(|e| AppError::TomlSerialize(e))?;
fs::write(&path, contents)?;
info!("Successfully saved tasks to {}.", path.display());
Ok(())
}