1use std::fmt;
2use colored::*;
3use std::{collections::HashMap, fs, path::PathBuf};
4use serde::{Serialize, Deserialize};
5
6#[derive(Serialize, Deserialize)]
7pub enum Priority {
8 High,
9 Medium,
10 Low
11}
12
13#[derive(Serialize, Deserialize)]
14pub struct Todo {
15 pub priority: Priority,
16 pub task: String,
17}
18
19impl Todo {
20 pub fn new(task: String, priority: Priority) -> Todo {
21 Todo { priority, task }
22 }
23}
24
25impl fmt::Display for Todo {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 let colored_star = match self.priority {
28 Priority::High => "[High]".red(),
29 Priority::Medium => "[Medium]".yellow(),
30 Priority::Low => "[Low]".green(),
31 };
32 write!(f, "{} {}", colored_star, self.task)
33 }
34}
35
36fn storage_path() -> PathBuf {
37 let mut path = dirs::home_dir().expect("Cannt find home directory");
38 path.push(".pchryss_todo_list.json");
39 path
40}
41
42pub fn load_todos() -> HashMap<u32, Todo> {
43 let path = storage_path();
44 if let Ok(data) = fs::read_to_string(&path) {
45 serde_json::from_str(&data).unwrap_or_default()
46 } else {
47 HashMap::new()
48 }
49}
50
51pub fn save_todos(todos: &HashMap<u32, Todo>) {
52 let path = storage_path();
53 let data = serde_json::to_string_pretty(todos).unwrap();
54 fs::write(path, data).unwrap();
55}