1use serde::{Deserialize, Serialize};
2use std::fs::{self, File};
3use std::io::{self, Read};
4use std::path::PathBuf;
5
6#[derive(Serialize, Deserialize, Debug, Clone)]
7pub struct TodoListLocation {
8 pub file_path: PathBuf,
9}
10
11impl Default for TodoListLocation {
12 fn default() -> Self {
13 let default_path = dirs::home_dir()
14 .unwrap_or_else(|| PathBuf::from("."))
15 .join("todo.md");
16
17 Self {
18 file_path: default_path,
19 }
20 }
21}
22
23impl TodoListLocation {
24 pub fn load() -> Self {
25 let config_path = get_config_file_path();
26
27 let config_file = match File::open(&config_path) {
28 Ok(file) => file,
29 Err(_) => {
30 eprintln!("Warning: Config file not found. Using default configuration.");
31 return TodoListLocation::default();
32 }
33 };
34
35 let mut reader = io::BufReader::new(config_file);
36 let mut contents = String::new();
37
38 if reader.read_to_string(&mut contents).is_err() {
39 eprintln!("Error: Failed to read config file. Using default configuration.");
40 return TodoListLocation::default();
41 }
42
43 match serde_json::from_str(&contents) {
44 Ok(config) => config,
45 Err(_) => {
46 eprintln!("Error: Failed to parse config file. Using default configuration.");
47 TodoListLocation::default()
48 }
49 }
50 }
51
52 pub fn save(&self) -> io::Result<()> {
53 let config_path = get_config_file_path();
54
55 if let Some(parent_path) = config_path.parent() {
56 fs::create_dir_all(parent_path)?;
57 }
58
59 let file = File::create(config_path)?;
60 serde_json::to_writer_pretty(file, self)?;
61
62 Ok(())
63 }
64
65 pub fn update_file_path(&mut self, path: PathBuf) {
66 self.file_path = path;
67 }
68}
69
70fn get_config_file_path() -> PathBuf {
71 let config_dir = dirs::config_dir()
72 .or_else(|| dirs::home_dir())
73 .unwrap_or_else(|| PathBuf::from("."));
74
75 config_dir.join("hw").join("config.json")
76}