File size: 2,146 Bytes
3d7d9b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use serde::{Deserialize, Serialize};
use std::sync::Mutex;
use tauri::{AppHandle, Manager};
use uuid::Uuid;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StudySession {
    pub id: String,
    pub title: String,
    pub duration_sec: u32,
    pub actual_sec: u32,
    pub reference_url: Option<String>,
    pub notes: String,
    pub created_at: i64,
}

#[derive(Default)]
pub struct StudyState {
    pub sessions: Mutex<Vec<StudySession>>,
}

#[tauri::command]
pub fn study_start(app: AppHandle, title: String, duration_sec: u32, reference_url: Option<String>) -> Result<StudySession, String> {
    let session = StudySession {
        id: Uuid::new_v4().to_string(),
        title,
        duration_sec,
        actual_sec: 0,
        reference_url,
        notes: String::new(),
        created_at: chrono::Utc::now().timestamp(),
    };
    let state = app.state::<StudyState>();
    let mut sessions = state.sessions.lock().map_err(|_| "study lock poisoned")?;
    sessions.push(session.clone());
    crate::persistence::save_json(&app, "study_sessions.json", &*sessions)?;
    Ok(session)
}

#[tauri::command]
pub fn study_complete(app: AppHandle, id: String, actual_sec: u32, notes: String) -> Result<StudySession, String> {
    let state = app.state::<StudyState>();
    let mut sessions = state.sessions.lock().map_err(|_| "study lock poisoned")?;
    let session = sessions.iter_mut().find(|s| s.id == id).ok_or("session not found")?;
    session.actual_sec = actual_sec;
    session.notes = notes;
    let result = session.clone();
    crate::persistence::save_json(&app, "study_sessions.json", &*sessions)?;
    Ok(result)
}

#[tauri::command]
pub fn study_list(app: AppHandle) -> Result<Vec<StudySession>, String> {
    let state = app.state::<StudyState>();
    let mut sessions = state.sessions.lock().map_err(|_| "study lock poisoned")?;
    if sessions.is_empty() {
        let loaded: Vec<StudySession> = crate::persistence::load_json(&app, "study_sessions.json")?;
        if !loaded.is_empty() { *sessions = loaded; }
    }
    Ok(sessions.clone())
}