1use serde::{Deserialize, Serialize};
4use std::path::Path;
5use std::fs;
6use chrono::prelude::*;
7use uuid::Uuid;
8use thiserror::Error;
9
10#[derive(Debug, Error)]
11pub enum TaskError {
12 #[error("Task not found")]
13 TaskNotFound,
14 #[error("IO error: {0}")]
15 IoError(#[from] std::io::Error),
16 #[error("Serialization error: {0}")]
17 SerializationError(#[from] serde_json::Error),
18}
19
20#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
22pub enum Priority {
23 Low,
24 Medium,
25 High,
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct Task {
31 pub id: String,
32 pub description: String,
33 pub priority: Priority,
34 pub created_at: DateTime<Utc>,
35 pub completed: bool,
36}
37
38#[derive(Debug, Serialize, Deserialize)]
40pub struct TaskManager {
41 tasks: Vec<Task>,
42}
43
44impl TaskManager {
45 pub fn new() -> Self {
47 TaskManager { tasks: Vec::new() }
48 }
49
50 pub fn add_task(&mut self, description: &str, priority: Priority) -> Result<(), TaskError> {
52 let task = Task {
53 id: Uuid::new_v4().to_string(),
54 description: description.to_string(),
55 priority,
56 created_at: Utc::now(),
57 completed: false,
58 };
59 self.tasks.push(task);
60 Ok(())
61 }
62
63 pub fn complete_task(&mut self, index: usize) -> Result<(), TaskError> {
65 if let Some(task) = self.tasks.get_mut(index) {
66 task.completed = true;
67 Ok(())
68 } else {
69 Err(TaskError::TaskNotFound)
70 }
71 }
72
73 pub fn tasks(&self) -> &Vec<Task> {
75 &self.tasks
76 }
77
78 pub fn save_to_file(&self, path: &Path) -> Result<(), TaskError> {
80 let serialized = serde_json::to_string_pretty(&self)?;
81 fs::write(path, serialized)?;
82 Ok(())
83 }
84
85 pub fn load_from_file(path: &Path) -> Result<Self, TaskError> {
87 let contents = fs::read_to_string(path)?;
88 let manager = serde_json::from_str(&contents)?;
89 Ok(manager)
90 }
91}
92
93impl Default for TaskManager {
94 fn default() -> Self {
95 Self::new()
96 }
97}