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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use std::{process::Command, str::FromStr};

type NoteId = u32;

#[derive(Debug, Clone)]
pub struct DnoteBook {
    pub name: String,
}

impl FromStr for DnoteBook {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let name = s.trim().to_string();
        Ok(DnoteBook { name })
    }
}

#[derive(Debug, Clone)]
pub struct DnotePage {
    pub id: NoteId,
    /// Truncated content from the page
    pub summary: String,
}

impl FromStr for DnotePage {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<&str> = s.split(')').collect();
        let id = parts[0]
            .trim()
            .trim_start_matches('(')
            .parse()
            .map_err(|_| ())?;
        let summary = parts[1]
            .trim()
            .trim_end_matches("[---More---]")
            .trim()
            .to_string();
        Ok(DnotePage { id, summary })
    }
}

#[derive(Debug, Clone)]
pub struct DnotePageInfo {
    pub content: String,
}

impl FromStr for DnotePageInfo {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let content = s.trim().to_string();
        Ok(DnotePageInfo { content })
    }
}

#[derive(Debug)]
pub enum DnoteCommand {
    Add {
        book_name: String,
        note: String,
    },
    ViewBooks,
    ViewByBook {
        book_name: String,
    },
    ViewByNoteId {
        note_id: NoteId,
    },
    EditNoteById {
        note_id: String,
        new_content: Option<String>,
        new_book: Option<String>,
    },
    EditBook {
        book_name: String,
        new_name: Option<String>,
    },
    RemoveBook {
        book_name: String,
    },
    RemoveNoteById {
        note_id: NoteId,
    },
}

#[derive(Debug)]
pub struct DnoteClient {}

#[derive(Debug)]
pub enum DnoteClientError {
    DnoteCommand,
    UTF8ParseError,
    ParseError,
    UnknownError,
}

impl DnoteClient {
    fn execute_command(&self, command: DnoteCommand) -> Result<String, DnoteClientError> {
        let (cmd, args) = match command {
            DnoteCommand::Add { book_name, note } => {
                let args = vec![book_name, "-c".to_string(), note];
                ("add", args)
            }
            DnoteCommand::ViewBooks => {
                let args = vec!["--name-only".to_string()];
                ("view", args)
            }
            DnoteCommand::ViewByBook { book_name } => {
                let args = vec![book_name];
                ("view", args)
            }
            DnoteCommand::ViewByNoteId { note_id } => {
                let args = vec![note_id.to_string(), "--content-only".to_string()];
                ("view", args)
            }
            DnoteCommand::EditNoteById {
                note_id,
                new_content,
                new_book,
            } => {
                let mut args = vec![note_id];
                if let Some(content) = new_content {
                    args.push("-c".to_string());
                    args.push(content);
                }
                if let Some(book) = new_book {
                    args.push("-b".to_string());
                    args.push(book);
                }
                ("edit", args)
            }
            DnoteCommand::EditBook {
                book_name,
                new_name,
            } => {
                let mut args = vec![book_name];
                if let Some(name) = new_name {
                    args.push("-n".to_string());
                    args.push(name);
                }
                ("edit", args)
            }
            DnoteCommand::RemoveBook { book_name } => {
                let args = vec![book_name];
                ("rm", args)
            }
            DnoteCommand::RemoveNoteById { note_id } => {
                let args = vec![note_id.to_string()];
                ("rm", args)
            }
        };
        let output = Command::new("dnote")
            .arg(cmd)
            .args(args)
            .output()
            .map_err(|_| DnoteClientError::DnoteCommand)?;
        let stdout: String =
            String::from_utf8(output.stdout).map_err(|_| DnoteClientError::UTF8ParseError)?;
        Ok(stdout)
    }

    pub fn get_books(&self) -> Result<Vec<DnoteBook>, DnoteClientError> {
        let output = self.execute_command(DnoteCommand::ViewBooks)?;
        let result: Result<Vec<DnoteBook>, _> = output.lines().map(|l| l.parse()).collect();
        result.map_err(|_| DnoteClientError::ParseError)
    }

    pub fn rename_book(
        &self,
        book_name: &str,
        new_book_name: &str,
    ) -> Result<(), DnoteClientError> {
        self.execute_command(DnoteCommand::EditBook {
            book_name: book_name.to_string(),
            new_name: Some(new_book_name.to_string()),
        })?;
        Ok(())
    }

    pub fn get_pages(&self, book_name: &str) -> Result<Vec<DnotePage>, DnoteClientError> {
        let output = self.execute_command(DnoteCommand::ViewByBook {
            book_name: book_name.to_string(),
        })?;
        let result: Result<Vec<DnotePage>, _> = output
            .lines()
            .skip(1) // skip first line e.g '  • on book ccu'
            .map(|l| l.parse())
            .collect();
        result.map_err(|_| DnoteClientError::ParseError)
    }

    pub fn get_page_content(&self, page_id: NoteId) -> Result<DnotePageInfo, DnoteClientError> {
        let output = self.execute_command(DnoteCommand::ViewByNoteId { note_id: page_id })?;
        output.parse().map_err(|_| DnoteClientError::ParseError)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn should_parse_dnotebook_from_string() {
        let s = String::from("my notebook");
        let book: DnoteBook = s.parse().unwrap();
        assert_eq!(book.name, "my notebook")
    }

    #[test]
    fn should_parse_dnotepage_from_string() {
        let input1 = "(21) # Issues [---More---]";
        let input2 = "  (27) # Missed [---More---]";
        let page1: DnotePage = input1.parse().unwrap();
        let page2: DnotePage = input2.parse().unwrap();
        assert_eq!(page1.id, 21);
        assert_eq!(page1.summary, "# Issues");
        assert_eq!(page2.id, 27);
        assert_eq!(page2.summary, "# Missed");
    }

    #[test]
    fn should_parse_dnotepageinfo_from_string() {
        let input1 = "# E2E\n\n- Grab a list of all data test ids on a page\n- Make sure all those data test ids exist";
        let input2 = "   # E2E   \n\n   - Grab a list of all data test ids on a page   \n   - Make sure all those data test ids exist   ";
        let input3 = "";
        let page_info1: DnotePageInfo = input1.parse().unwrap();
        let page_info2: DnotePageInfo = input2.parse().unwrap();
        let page_info3: DnotePageInfo = input3.parse().unwrap();
        assert_eq!(page_info1.content, input1);
        assert_eq!(page_info2.content, input2.trim());
        assert_eq!(page_info3.content, input3);
    }
}