File size: 1,732 Bytes
9982ad3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use rusqlite::{Connection, Result};
use crate::whiteboard::DrawAction;
use std::sync::Mutex;

pub struct Database {
    conn: Mutex<Connection>,
}

impl Database {
    pub fn new(conn: Connection) -> Self {
        Database { conn: Mutex::new(conn) }
    }

    pub fn save_action(&self, action: &DrawAction) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute(
            "INSERT INTO actions (x, y, color, is_eraser, pen_size) VALUES (?1, ?2, ?3, ?4, ?5)",
            (action.x, action.y, &action.color, action.is_eraser, action.pen_size),
        )?;
        Ok(())
    }

    pub fn get_current_state(&self) -> Result<Vec<DrawAction>> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn.prepare("SELECT x, y, color, is_eraser, pen_size FROM actions ORDER BY id")?;
        let actions = stmt.query_map([], |row| {
            Ok(DrawAction {
                x: row.get(0)?,
                y: row.get(1)?,
                color: row.get(2)?,
                is_eraser: row.get(3)?,
                pen_size: row.get(4)?,
            })
        })?;
        actions.collect()
    }

    pub fn clear_whiteboard(&self) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute("DELETE FROM actions", [])?;
        Ok(())
    }
}

pub fn init_db() -> Result<Database> {
    let conn = Connection::open("whiteboard.db")?;
    conn.execute(
        "CREATE TABLE IF NOT EXISTS actions (
            id INTEGER PRIMARY KEY,
            x REAL NOT NULL,
            y REAL NOT NULL,
            color TEXT NOT NULL,
            is_eraser BOOLEAN NOT NULL,
            pen_size REAL NOT NULL
        )",
        [],
    )?;
    Ok(Database::new(conn))
}