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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! Handle the archiving of old records from the timelog.

use std::fmt::{self, Display};
use std::fs::{rename, File, OpenOptions};
use std::io::prelude::*;
use std::io::{BufRead, BufReader, BufWriter};
use std::path::Path;

use crate::config::Config;
#[doc(inline)]
use crate::date::Date;
#[doc(inline)]
use crate::entry::{Entry, EntryError};
#[doc(inline)]
use crate::error::Error;
#[doc(inline)]
use crate::error::PathError;
#[doc(inline)]
use crate::logfile::Logfile;
use crate::Result;

#[derive(Debug, Default)]
struct EntryLine {
    comments: Vec<String>,
    line:     Option<String>
}

// Representation of an entry line with optional leading comment lines.
impl EntryLine {
    // Add an optional text line to the [`EntryLine`] object.
    //
    // If the supplied optional line is None, do nothing and return false.
    // If the supplied line starts with the comment character, store as leading
    // comment and return false.
    // If the supplied line is not a comment, add as the entry line and return true.
    fn add_line<OS>(&mut self, oline: OS) -> bool
    where
        OS: Into<Option<String>>
    {
        if let Some(line) = oline.into() {
            if Entry::is_comment_line(&line) {
                self.comments.push(line);
            }
            else {
                self.line = Some(line);
                return true;
            }
        }
        false
    }

    // Extract the year from the contained [`EntryLine`] returning an optional year number.
    fn extract_year(&self) -> Option<i32> {
        self.line.as_ref().and_then(|ln| Entry::extract_year(ln))
    }

    // Return true if there is an entry line and it is a stop.
    fn is_stop_line(&self) -> bool { self.line.as_ref().map_or(false, |l| Entry::is_stop_line(l)) }

    // Convert the entry line to an entry if it parses and exists.
    //
    // Return None if no Entry line exists.
    // Return Some(Err(EntryError)) if the Entry conversion fails.
    fn to_entry(&self) -> Option<std::result::Result<Entry, EntryError>> {
        self.line.as_ref().map(|l| Entry::from_line(l))
    }

    // Convert the [`EntryLine`] to an optional EntryLine.
    //
    // If there are no comments and no entry line, return None.
    // Otherwise, return itself as a Some().
    fn make_option(self) -> Option<Self> {
        (!self.comments.is_empty() || self.line.is_some()).then_some(self)
    }
}

impl Display for EntryLine {
    // Format the [`EntryLine`] for display.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut iter = self.comments.iter().chain(self.line.iter());
        if let Some(line) = iter.next() {
            write!(f, "{line}")?;
            for line in iter {
                write!(f, "\n{line}")?;
            }
        }
        Ok(())
    }
}

// Iterator that returns [`EntryLine`]s.
struct EntryLineIter<'a> {
    lines: std::io::Lines<BufReader<&'a File>>
}

impl<'a> EntryLineIter<'a> {
    // Create an [`EntryLineIter`] from a [`File`] reference.
    #[rustfmt::skip]
    pub fn new(file: &'a File) -> Self {
        Self { lines: BufReader::new(file).lines() }
    }
}

impl<'a> Iterator for EntryLineIter<'a> {
    type Item = EntryLine;

    // Return next [`EntryLine`] if it exists.
    fn next(&mut self) -> Option<Self::Item> {
        let mut eline = EntryLine::default();
        for line in self.lines.by_ref() {
            if eline.add_line(line.ok()) {
                return eline.make_option();
            }
        }
        eline.make_option()
    }
}

/// Clone supplied [`Entry`] moved to the beginning of the next year
fn entry_next_year(entry: &Entry) -> Entry {
    Entry::new(
        entry.entry_text(),
        crate::date::DateTime::new((entry.date().year() + 1, 1, 1), (0, 0, 0)).unwrap()
    )
}

/// Clone supplied [`Entry`] moved to the beginning of the next year
#[rustfmt::skip]
fn entry_end_year(entry: &Entry) -> Entry {
    Entry::new_stop(
        crate::date::DateTime::new((entry.date().year() + 1, 1, 1), (0, 0, 0)).unwrap()
    )
}

/// Configuration for archiving previous year information from the timelog.txt file.
pub(crate) struct Archiver<'a> {
    // Reference to the rtimelog configuration.
    config:    &'a Config,
    // The current year
    curr_year: i32,
    // The name for the new file created to store the previous year.
    new_file:  String,
    // The name for the backup file.
    back_file: String
}

impl<'a> Archiver<'a> {
    /// Create a new Archiver object.
    pub(crate) fn new(config: &'a Config) -> Self {
        Self {
            config,
            curr_year: Date::today().year(),
            new_file: format!("{}.new", config.logfile()),
            back_file: format!("{}.bak", config.logfile())
        }
    }

    // Return the [`Logfile`] object representing the file on disk
    //
    // # Errors
    //
    // - Return [`PathError::FilenameMissing`] if the `file` has no filename.
    // - Return [`PathError::InvalidPath`] if the path part of `file` is not a valid path.
    fn logfile(&self) -> Result<Logfile> { Ok(Logfile::new(&self.config.logfile())?) }

    // Return an appropriate path/filename for the supplied year.
    fn archive_filepath(&self, year: i32) -> String {
        format!("{}/timelog-{}.txt", self.config.dir(), year)
    }

    // Return a [`BufWriter`] wrapping the file for writing to the supplied filename.
    //
    // # Errors
    //
    // - Return [`PathError::FileAccess`] if unable to open the file.
    fn archive_writer(filename: &str) -> Result<BufWriter<File>> {
        let file = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(filename)
            .map_err(|e| PathError::FileAccess(filename.to_string(), e.to_string()))?;
        Ok(BufWriter::new(file))
    }

    /// Archive the first (non-current) year from the logfile.
    ///
    /// - Return Ok(Some(year)) if `year` was archived.
    /// - Return Ok(None) if no previous year to archive.
    ///
    /// # Errors
    ///
    /// - Return [`Error::PathError`] for any error accessing the log or archive files.
    pub(crate) fn archive(&self) -> Result<Option<i32>> {
        let file = self.logfile()?.open()?;
        // let mut lines = BufReader::new(file).lines();
        let mut elines = EntryLineIter::new(&file);
        let first = match elines.next() {
            Some(line) => line,
            _ => return Ok(None)
        };
        let arc_year = first.extract_year().ok_or(EntryError::InvalidTimeStamp)?;
        if arc_year >= self.curr_year {
            return Ok(None);
        }

        let logfile = self.config.logfile();
        let archive_filename = self.archive_filepath(arc_year);
        if Path::new(&archive_filename).exists() {
            return Err(Error::from(PathError::AlreadyExists(archive_filename)));
        }
        let mut arc_stream = Self::archive_writer(&archive_filename)?;
        let mut new_stream = Self::archive_writer(&self.new_file)?;

        writeln!(&mut arc_stream, "{first}")
            .map_err(|e| PathError::FileWrite(archive_filename.clone(), e.to_string()))?;

        let mut prev = Some(first);
        let mut save = false;
        for line in elines {
            save = line.extract_year().map_or(save, |y| y == arc_year);

            let mut stream = if save {
                &mut arc_stream
            }
            else if let Some(pline) = prev {
                if !pline.is_stop_line() {
                    if let Some(ev) = pline.to_entry() {
                        let entry = ev?;
                        // finish archive file
                        writeln!(&mut arc_stream, "{}", entry_end_year(&entry)).map_err(|e| {
                            PathError::FileWrite(archive_filename.clone(), e.to_string())
                        })?;
                        // start new file
                        writeln!(&mut new_stream, "{}", entry_next_year(&entry)).map_err(|e| {
                            PathError::FileWrite(archive_filename.clone(), e.to_string())
                        })?;
                    }
                }
                prev = None;
                &mut new_stream
            }
            else {
                &mut new_stream
            };

            writeln!(&mut stream, "{line}")
                .map_err(|e| PathError::FileWrite(archive_filename.clone(), e.to_string()))?;
            if save {
                prev = Some(line);
            }
        }

        Self::flush(&archive_filename, &mut arc_stream)?;
        Self::flush(&self.new_file, &mut new_stream)?;
        Self::rename(&logfile, &self.back_file)?;
        Self::rename(&self.new_file, &logfile)?;

        Ok(Some(arc_year))
    }

    // Utility method for flushing a writer and properly reporting any error.
    fn flush(filename: &str, stream: &mut BufWriter<File>) -> Result<()> {
        stream
            .flush()
            .map_err(|e| PathError::FileWrite(filename.to_string(), e.to_string()).into())
    }

    // Utility method for renaming a file and properly reporting any error.
    fn rename(old: &str, new: &str) -> Result<()> {
        rename(old, new)
            .map_err(|e| PathError::RenameFailure(old.to_string(), e.to_string()).into())
    }
}

#[cfg(test)]
mod tests {
    use std::fs::OpenOptions;
    use std::iter::once;

    use spectral::prelude::*;
    use tempfile::TempDir;

    use super::*;
    use crate::Date;

    fn make_timelog(lines: &Vec<String>) -> (TempDir, String) {
        let tmpdir = TempDir::new().expect("Cannot make tempfile");
        let mut path = tmpdir.path().to_path_buf();
        path.push("timelog.txt");
        let filename = path.to_str().unwrap();
        let file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(filename)
            .unwrap();
        let mut stream = BufWriter::new(file);
        lines
            .iter()
            .for_each(|line| writeln!(&mut stream, "{}", line).unwrap());
        stream.flush().unwrap();
        (tmpdir, filename.to_string())
    }

    #[test]
    fn test_new() {
        let config = Config::default();
        let arch = Archiver::new(&config);
        let logfile = config.logfile();
        assert_that!(arch.config).is_equal_to(&config);
        assert_that!(arch.curr_year).is_equal_to(&(Date::today().year()));
        assert_that!(arch.new_file).is_equal_to(&format!("{}.new", logfile));
        assert_that!(arch.back_file).is_equal_to(&format!("{}.bak", logfile));
    }

    #[test]
    fn test_archive_filepath() {
        let config = Config::default();
        let arch = Archiver::new(&config);
        let expect = format!("{}/timelog-{}.txt", config.dir(), 2011);
        assert_that!(arch.archive_filepath(2011)).is_equal_to(&expect);
    }

    #[test]
    fn test_archive_this_year() {
        let curr_year = Date::today().year();
        let (tmpdir, _filename) = make_timelog(&vec![
            format!("{}-02-10 09:01:00 +foo", curr_year),
            format!("{}-02-10 09:10:00 stop", curr_year),
            format!("{}-02-15 09:01:00 +foo", curr_year),
            format!("{}-02-15 09:01:00 stop", curr_year),
        ]);
        #[rustfmt::skip]
        let config = Config::new(
            ".timelog",
            Some(tmpdir.path().to_str().expect("tempdir failed to return string")),
            Some("vim"),
            None,
            None
        ).expect("Legal config");
        let arch = Archiver::new(&config);
        assert_that!(arch.archive()).is_ok().is_none();
    }

    #[test]
    fn test_archive_this_year_with_comments() {
        let curr_year = Date::today().year();
        let (tmpdir, _filename) = make_timelog(&vec![
            String::from("# Initial comment"),
            format!("{}-02-10 09:01:00 +foo", curr_year),
            format!("{}-02-10 09:10:00 stop", curr_year),
            String::from("# Middle comment"),
            format!("{}-02-15 09:01:00 +foo", curr_year),
            format!("{}-02-15 09:01:00 stop", curr_year),
            String::from("# Trailing comment"),
        ]);
        #[rustfmt::skip]
        let config = Config::new(
            ".timelog",
            Some(tmpdir.path().to_str().expect("tempdir failed to return string")),
            Some("vim"),
            None,
            None
        ).expect("Legal config");
        let arch = Archiver::new(&config);
        assert_that!(arch.archive()).is_ok().is_none();
    }

    #[test]
    fn test_archive_prev_year() {
        let prev_year = Date::today().year() - 1;
        let (tmpdir, filename) = make_timelog(&vec![
            format!("{}-02-10 09:01:00 +foo", prev_year),
            format!("{}-02-10 09:10:00 stop", prev_year),
            format!("{}-02-15 09:01:00 +foo", prev_year),
            format!("{}-02-15 09:01:00 stop", prev_year),
        ]);
        let expected = std::fs::read_to_string(&filename).expect("Could not read archive");
        #[rustfmt::skip]
        let config = Config::new(
            ".timelog",
            Some(tmpdir.path().to_str().expect("tempdir failed to return string")),
            Some("vim"),
            None,
            None
        ).expect("Legal config");
        let arch = Archiver::new(&config);
        assert_that!(arch.archive()).is_ok().contains(prev_year);

        let archive_file = arch.archive_filepath(prev_year);
        let actual = std::fs::read_to_string(&archive_file).expect("Could not read archive");
        assert_that!(actual).is_equal_to(&expected);

        let metadata = std::fs::metadata(&filename).expect("metadata failed");
        assert_that!(metadata.is_file()).is_true();
        assert_that!(metadata.len()).is_equal_to(0u64);
    }

    #[test]
    fn test_archive_split_years() {
        let curr_year = Date::today().year();
        let prev_year = curr_year - 1;
        let prev_year_lines = vec![
            format!("{}-12-10 19:01:00 +foo", prev_year),
            format!("{}-12-10 19:10:00 stop", prev_year),
            format!("{}-12-15 19:01:00 +foo", prev_year),
            format!("{}-12-15 19:01:00 stop", prev_year),
        ];
        let curr_year_lines = vec![
            format!("{}-02-10 09:01:00 +foo", curr_year),
            format!("{}-02-10 09:10:00 stop", curr_year),
            format!("{}-02-15 09:01:00 +foo", curr_year),
            format!("{}-02-15 09:01:00 stop", curr_year),
        ];
        let mut expected = curr_year_lines.join("\n");
        expected.push_str("\n");
        let lines: Vec<String> = prev_year_lines
            .iter()
            .chain(curr_year_lines.iter())
            .cloned()
            .collect();
        let (tmpdir, filename) = make_timelog(&lines);
        #[rustfmt::skip]
        let config = Config::new(
            ".timelog",
            Some(tmpdir.path().to_str().expect("tempdir failed to return string")),
            Some("vim"),
            None,
            None
        ).expect("Legal config");
        let arch = Archiver::new(&config);
        assert_that!(arch.archive()).is_ok().contains(prev_year);

        let actual = std::fs::read_to_string(&filename).expect("Could not read archive");
        assert_that!(actual).is_equal_to(&expected);

        let mut expected = prev_year_lines.join("\n");
        expected.push_str("\n");
        let archive_file = arch.archive_filepath(prev_year);
        let actual = std::fs::read_to_string(&archive_file).expect("Could not read archive");
        assert_that!(actual).is_equal_to(&expected);
    }

    #[test]
    fn test_archive_split_years_with_comments() {
        let curr_year = Date::today().year();
        let prev_year = curr_year - 1;
        let prev_year_lines = vec![
            String::from("# Initial commment"),
            format!("{}-12-10 19:01:00 +foo", prev_year),
            format!("{}-12-10 19:10:00 stop", prev_year),
            format!("{}-12-15 19:01:00 +foo", prev_year),
            format!("{}-12-15 19:01:00 stop", prev_year),
        ];
        let curr_year_lines = vec![
            String::from("# Breaking commment"),
            format!("{}-02-10 09:01:00 +foo", curr_year),
            format!("{}-02-10 09:10:00 stop", curr_year),
            format!("{}-02-15 09:01:00 +foo", curr_year),
            format!("{}-02-15 09:01:00 stop", curr_year),
            String::from("# Trailing commment"),
        ];
        let mut expected = curr_year_lines.join("\n");
        expected.push_str("\n");
        let lines: Vec<String> = prev_year_lines
            .iter()
            .chain(curr_year_lines.iter())
            .cloned()
            .collect();
        let (tmpdir, filename) = make_timelog(&lines);
        #[rustfmt::skip]
        let config = Config::new(
            ".timelog",
            Some(tmpdir.path().to_str().expect("tempdir failed to return string")),
            Some("vim"),
            None,
            None
        ).expect("Legal config");
        let arch = Archiver::new(&config);
        assert_that!(arch.archive()).is_ok().contains(prev_year);

        let actual = std::fs::read_to_string(&filename).expect("Could not read archive");
        assert_that!(actual).is_equal_to(&expected);

        let mut expected = prev_year_lines.join("\n");
        expected.push_str("\n");
        let archive_file = arch.archive_filepath(prev_year);
        let actual = std::fs::read_to_string(&archive_file).expect("Could not read archive");
        assert_that!(actual).is_equal_to(&expected);
    }

    #[test]
    fn test_archive_split_years_task_crosses() {
        let curr_year = Date::today().year();
        let prev_year = curr_year - 1;
        let prev_year_lines = vec![
            format!("{}-12-10 19:01:00 +foo", prev_year),
            format!("{}-12-10 19:10:00 stop", prev_year),
            format!("{}-12-15 19:01:00 +foo", prev_year),
            format!("{}-12-15 19:01:00 stop", prev_year),
            format!("{}-12-31 23:01:00 +bar", prev_year),
        ];
        let curr_year_lines = vec![
            format!("{}-01-01 00:10:00 stop", curr_year),
            format!("{}-02-10 09:01:00 +foo", curr_year),
            format!("{}-02-10 09:10:00 stop", curr_year),
            format!("{}-02-15 09:01:00 +foo", curr_year),
            format!("{}-02-15 09:01:00 stop", curr_year),
        ];
        let mut expected = once(&format!("{}-01-01 00:00:00 +bar", curr_year))
            .chain(curr_year_lines.iter())
            .cloned()
            .collect::<Vec<String>>()
            .join("\n");
        expected.push_str("\n");
        let lines: Vec<String> = prev_year_lines
            .iter()
            .chain(curr_year_lines.iter())
            .cloned()
            .collect();
        let (tmpdir, filename) = make_timelog(&lines);
        #[rustfmt::skip]
        let config = Config::new(
            ".timelog",
            Some(tmpdir.path().to_str().expect("tempdir failed to return string")),
            Some("vim"),
            None,
            None
        ).expect("Legal config");
        let arch = Archiver::new(&config);
        assert_that!(arch.archive()).is_ok().contains(prev_year);

        let actual = std::fs::read_to_string(&filename).expect("Could not read archive");
        assert_that!(actual).is_equal_to(&expected);

        let mut expected = prev_year_lines
            .iter()
            .chain(once(&format!("{}-01-01 00:00:00 stop", curr_year)))
            .cloned()
            .collect::<Vec<String>>()
            .join("\n");
        expected.push_str("\n");
        let archive_file = arch.archive_filepath(prev_year);
        let actual = std::fs::read_to_string(&archive_file).expect("Could not read archive");
        assert_that!(actual).is_equal_to(&expected);
    }

    #[test]
    fn test_archive_split_years_task_crosses_with_comments() {
        let curr_year = Date::today().year();
        let prev_year = curr_year - 1;
        let prev_year_lines = vec![
            String::from("# Initial comment"),
            format!("{}-12-10 19:01:00 +foo", prev_year),
            format!("{}-12-10 19:10:00 stop", prev_year),
            format!("{}-12-15 19:01:00 +foo", prev_year),
            format!("{}-12-15 19:01:00 stop", prev_year),
            format!("{}-12-31 23:01:00 +bar", prev_year),
        ];
        let curr_year_lines = vec![
            String::from("# Split comment"),
            format!("{}-01-01 00:10:00 stop", curr_year),
            format!("{}-02-10 09:01:00 +foo", curr_year),
            format!("{}-02-10 09:10:00 stop", curr_year),
            format!("{}-02-15 09:01:00 +foo", curr_year),
            format!("{}-02-15 09:01:00 stop", curr_year),
            String::from("# Trailing comment"),
        ];
        let mut expected = once(&format!("{}-01-01 00:00:00 +bar", curr_year))
            .chain(curr_year_lines.iter())
            .cloned()
            .collect::<Vec<String>>()
            .join("\n");
        expected.push_str("\n");
        let lines: Vec<String> = prev_year_lines
            .iter()
            .chain(curr_year_lines.iter())
            .cloned()
            .collect();
        let (tmpdir, filename) = make_timelog(&lines);
        #[rustfmt::skip]
        let config = Config::new(
            ".timelog",
            Some(tmpdir.path().to_str().expect("tempdir failed to return string")),
            Some("vim"),
            None,
            None
        ).expect("Legal config");
        let arch = Archiver::new(&config);
        assert_that!(arch.archive()).is_ok().contains(prev_year);

        let actual = std::fs::read_to_string(&filename).expect("Could not read archive");
        assert_that!(actual).is_equal_to(&expected);

        let mut expected = prev_year_lines
            .iter()
            .chain(once(&format!("{}-01-01 00:00:00 stop", curr_year)))
            .cloned()
            .collect::<Vec<String>>()
            .join("\n");
        expected.push_str("\n");
        let archive_file = arch.archive_filepath(prev_year);
        let actual = std::fs::read_to_string(&archive_file).expect("Could not read archive");
        assert_that!(actual).is_equal_to(&expected);
    }
}