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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
//! Interface to the stack file for the timelog application.
//!
//! # Examples
//!
//! ```rust
//! use timelog::stack::Stack;
//! # fn main() -> Result<(), timelog::Error> {
//! let stack = Stack::new("./stack.txt" )?;
//!
//! stack.push("+Project @Task More detail");
//! let task = stack.pop().expect("Can't pop task");
//! println!("{:?}", task);
//! stack.clear();
//! #   Ok(())
//! # }
//! ```

use std::fs::{canonicalize, remove_file, rename, File};
use std::io::prelude::*;
use std::io::{BufRead, BufReader, BufWriter};
use std::path::{Path, PathBuf};

#[doc(inline)]
use crate::error::{Error, PathError};
#[doc(inline)]
use crate::file::{append_open, pop_last_line, rw_open};
use crate::Result;

/// Represent the stack file on disk.
#[derive(Debug)]
pub struct Stack(String);

impl Stack {
    /// Creates a [`Stack`] object wrapping the supplied file.
    ///
    /// ## Errors
    ///
    /// - Return [`PathError::FilenameMissing`] if the `file` has no filename.
    /// - Return [`PathError::InvalidPath`] if the path part of `file` is not a valid path.
    pub fn new(file: &str) -> std::result::Result<Self, PathError> {
        if file.is_empty() {
            return Err(PathError::FilenameMissing);
        }
        let mut dir = PathBuf::from(file);
        let filename = dir
            .file_name()
            .ok_or(PathError::FilenameMissing)?
            .to_os_string();
        dir.pop();

        let mut candir = canonicalize(dir)
            .map_err(|e| PathError::InvalidPath(file.to_owned(), e.to_string()))?;
        candir.push(filename);
        Ok(Self(candir.to_str().unwrap().to_owned()))
    }

    /// Open the stack file for reading, return a [`File`].
    ///
    /// ## Errors
    ///
    /// - Return [`PathError::FileAccess`] if unable to open the file.
    pub fn open(&self) -> std::result::Result<File, PathError> {
        File::open(&self.0).map_err(|e| PathError::FileAccess(self.0.to_owned(), e.to_string()))
    }

    // Open the stack file for reading and writing, return a [`File`].
    //
    // ## Errors
    //
    // - Return [`PathError::FileAccess`] if unable to open the file.
    // fn rw_open(&self) -> std::result::Result<File, PathError> {
    //     OpenOptions::new()
    //         .read(true)
    //         .write(true)
    //         .open(&self.0)
    //         .map_err(|e| PathError::FileAccess(self.clone_file(), e.to_string()))
    // }

    // Clone the filename
    fn clone_file(&self) -> String { self.0.to_owned() }

    /// Return `true` if the timelog file exists
    pub fn exists(&self) -> bool { Path::new(&self.0).exists() }

    /// Truncates the stack file, removing all items from the stack.
    ///
    /// ## Errors
    ///
    /// - Return [`PathError::FileAccess`] if the stack file is not accessible.
    pub fn clear(&self) -> std::result::Result<(), PathError> {
        remove_file(&self.0).map_err(|e| PathError::FileAccess(self.clone_file(), e.to_string()))
    }

    /// Adds a new event to the stack file.
    ///
    /// ## Errors
    ///
    /// - Return [`PathError::FileAccess`] if the stack file cannot be opened or created.
    /// - Return [`PathError::FileWrite`] if the stack file cannot be written.
    pub fn push(&self, task: &str) -> std::result::Result<(), PathError> {
        let file = append_open(&self.0)?;
        let mut stream = BufWriter::new(file);
        writeln!(&mut stream, "{}", task)
            .map_err(|e| PathError::FileWrite(self.clone_file(), e.to_string()))?;
        stream
            .flush()
            .map_err(|e| PathError::FileWrite(self.clone_file(), e.to_string()))?;
        Ok(())
    }

    /// Remove the most recent task from the stack file and return the task string.
    pub fn pop(&self) -> Option<String> {
        let mut file = rw_open(&self.0).ok()?;
        pop_last_line(&mut file)
    }

    /// Remove one or more tasks from the stack file.
    ///
    /// If `arg` is 0, remove one item.
    /// If `arg` is a positive number, remove that many items from the stack.
    ///
    /// ## Errors
    ///
    /// - Return [`Error::StackPop`] if attempts to pop more items than exist in the stack file.
    pub fn drop(&self, arg: u32) -> Result<()> {
        (0..std::cmp::max(1, arg))
            .try_for_each(|_| self.pop().map(|_| ()))
            .ok_or(Error::StackPop)
    }

    /// Remove everything except the top `num` tasks from the stack.
    pub fn keep(&self, num: u32) -> Result<()> {
        let file = self.open()?;
        let len = BufReader::new(file).lines().count();

        if len > num as usize {
            let backfile = format!("{}-bak", self.0);
            let outfile = append_open(&backfile)?;
            let mut stream = BufWriter::new(outfile);
            let file = self.open()?;
            for line in BufReader::new(file).lines().skip(len - num as usize) {
                writeln!(&mut stream, "{}", line.unwrap())
                    .map_err(|e| PathError::FileWrite(self.clone_file(), e.to_string()))?;
            }
            stream
                .flush()
                .map_err(|e| PathError::FileWrite(self.clone_file(), e.to_string()))?;

            rename(&backfile, &self.clone_file())
                .map_err(|e| PathError::RenameFailure(self.clone_file(), e.to_string()))?;
        }
        Ok(())
    }

    /// Format the stack as a [`String`].
    ///
    /// The stack will be formatted such that the most recent item is listed
    /// first.
    pub fn list(&self) -> String {
        let file = match File::open(&self.0) {
            Ok(f) => f,
            Err(_) => return String::new(),
        };
        let lines: Vec<String> = BufReader::new(file).lines().map(|rl| rl.unwrap()).collect();
        let output = String::new();
        lines.iter().rev().fold(output, |mut acc, l| {
            acc.push_str(l);
            acc.push('\n');
            acc
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use spectral::prelude::*;
    use tempfile::TempDir;

    use std::path::Path;

    #[test]
    fn test_new_missing_file() {
        assert_that!(Stack::new("")).is_err_containing(PathError::FilenameMissing);
    }

    #[test]
    fn test_new_bad_path() {
        let mut stackdir = TempDir::new()
            .expect("Cannot make tempdir")
            .path()
            .to_path_buf();
        stackdir.push("foo");
        stackdir.push("stack.txt");

        let file = stackdir.as_path().to_str().unwrap();
        assert_that!(Stack::new(file)).is_err_containing(PathError::InvalidPath(
            file.to_owned(),
            "No such file or directory (os error 2)".to_string(),
        ));
    }

    #[test]
    fn test_new() {
        let tmpdir = TempDir::new().expect("Cannot make tempfile");
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let filename = path.to_str().unwrap();
        assert_that!(Stack::new(filename)).is_ok();
    }

    #[test]
    fn test_push() {
        let tmpdir = TempDir::new().expect("Cannot make tempfile");
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let filename = path.to_str().unwrap();
        let stack = Stack::new(filename).expect("Cannot create stack");
        assert_that!(Path::new(filename).exists()).is_false();

        let task = "+house @todo change filters";
        assert_that!(stack.push(task)).is_ok();
        let path = Path::new(filename);
        assert_that!(path.is_file()).is_true();

        // test file length and handle newline lengths
        let filelen = path.metadata().expect("metadata fail").len() as usize;
        assert_that!(filelen).is_equal_to(task.len() + 1);

        assert_that!(stack.push(task)).is_ok();
        let filelen = path.metadata().expect("metadata fail").len() as usize;
        assert_that!(filelen).is_equal_to(2 * task.len() + 2);
    }

    #[test]
    fn test_pop() {
        let tmpdir = TempDir::new().expect("Cannot make tempfile");
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let filename = path.to_str().unwrap();
        let mut file = File::create(filename).expect("Cannot create file");
        file.write_all(b"+home @todo first\n+home @todo second\n")
            .expect("Cannot fill file");

        let stack = Stack::new(filename).expect("Cannot create stack");
        assert_that!(stack.pop()).contains(String::from("+home @todo second"));
        assert_that!(stack.pop()).contains(String::from("+home @todo first"));

        let path = Path::new(filename);
        assert_that!(path.is_file()).is_true();
        // test file length and handle newline lengths
        let filelen = path.metadata().expect("metadata fail").len() as usize;
        assert_that!(filelen).is_equal_to(0);
    }

    #[test]
    fn test_clear() {
        let tmpdir = TempDir::new().expect("Cannot make tempfile");
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let filename = path.to_str().unwrap();
        let mut file = File::create(filename).expect("Cannot create file");
        file.write_all(b"+home @todo first\n+home @todo second\n")
            .expect("Cannot fill file");

        let stack = Stack::new(filename).expect("Cannot create stack");
        assert_that!(stack.clear()).is_ok();
        assert_that!(Path::new(filename).exists()).is_false();
    }

    #[test]
    fn test_drop_0() {
        let tmpdir = TempDir::new().expect("Cannot make tempfile");
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let filename = path.to_str().unwrap();
        let mut file = File::create(filename).expect("Cannot create file");
        file.write_all(b"+home @todo first\n+home @todo second\n")
            .expect("Cannot fill file");

        let stack = Stack::new(filename).expect("Cannot create stack");
        assert_that!(stack.drop(0)).is_ok();
        assert_that!(stack.pop()).contains(String::from("+home @todo first"));
    }

    #[test]
    fn test_drop_1() {
        let tmpdir = TempDir::new().expect("Cannot make tempfile");
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let filename = path.to_str().unwrap();
        let mut file = File::create(filename).expect("Cannot create file");
        file.write_all(b"+home @todo first\n+home @todo second\n")
            .expect("Cannot fill file");

        let stack = Stack::new(filename).expect("Cannot create stack");
        assert_that!(stack.drop(1)).is_ok();
        assert_that!(stack.pop()).contains(String::from("+home @todo first"));
    }

    #[test]
    fn test_drop_2() {
        let tmpdir = TempDir::new().expect("Cannot make tempfile");
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let filename = path.to_str().unwrap();
        let mut file = File::create(filename).expect("Cannot create file");
        file.write_all(b"+home @todo first\n+home @todo second\n+home @todo third\n")
            .expect("Cannot fill file");

        let stack = Stack::new(filename).expect("Cannot create stack");
        assert_that!(stack.drop(2)).is_ok();
        assert_that!(stack.pop()).contains(String::from("+home @todo first"));
    }

    #[test]
    fn test_list() {
        let tmpdir = TempDir::new().expect("Cannot make tempfile");
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let filename = path.to_str().unwrap();
        let mut file = File::create(filename).expect("Cannot create file");
        file.write_all(b"+home @todo first\n+home @todo second\n+home @todo third\n")
            .expect("Cannot fill file");

        let stack = Stack::new(filename).expect("Cannot create stack");
        assert_that!(stack.list()).is_equal_to(String::from(
            "+home @todo third\n+home @todo second\n+home @todo first\n",
        ));
    }
}