summaryrefslogtreecommitdiff
path: root/src-tauri/src/storage.rs
blob: 28b1f86ca9c0ca9df8875d0745b64b80921f5eae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use std::fs;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Settings {
    pub work_duration_secs: u64,
    pub short_break_secs: u64,
    pub long_break_secs: u64,
    pub sessions_before_long_break: u32,
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            work_duration_secs: 25 * 60,
            short_break_secs: 5 * 60,
            long_break_secs: 15 * 60,
            sessions_before_long_break: 4,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Task {
    pub id: String,
    pub name: String,
    pub total_sessions: u32,
    pub remaining_sessions: u32,
    pub completed: bool,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppData {
    pub settings: Settings,
    pub tasks: Vec<Task>,
    pub current_task_id: Option<String>,
}

impl Default for AppData {
    fn default() -> Self {
        Self {
            settings: Settings::default(),
            tasks: Vec::new(),
            current_task_id: None,
        }
    }
}

pub fn data_path(app_data_dir: &PathBuf) -> PathBuf {
    app_data_dir.join("data.json")
}

pub fn load(app_data_dir: &PathBuf) -> AppData {
    let path = data_path(app_data_dir);
    if !path.exists() {
        return AppData::default();
    }
    match fs::read_to_string(&path) {
        Ok(contents) => serde_json::from_str(&contents).unwrap_or_default(),
        Err(_) => AppData::default(),
    }
}

pub fn save(app_data_dir: &PathBuf, data: &AppData) -> Result<(), String> {
    fs::create_dir_all(app_data_dir)
        .map_err(|e| format!("Failed to create data directory: {}", e))?;
    let path = data_path(app_data_dir);
    let contents = serde_json::to_string_pretty(data)
        .map_err(|e| format!("Failed to serialize data: {}", e))?;
    fs::write(&path, contents)
        .map_err(|e| format!("Failed to write data file: {}", e))?;
    Ok(())
}