summaryrefslogtreecommitdiffstats
path: root/lib/domain/libimagdiary/src/iter.rs
blob: c6e8f542278e8230a9ca0d76b6608106fc3bb7a2 (plain)
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
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::fmt::{Debug, Formatter, Error as FmtError};
use std::result::Result as RResult;

use filters::filter::Filter;

use libimagstore::storeid::StoreIdIterator;
use libimagstore::storeid::StoreId;

use crate::is_in_diary::IsInDiary;
use anyhow::Result;



/// A iterator for iterating over diary entries
pub struct DiaryEntryIterator {
    name: String,
    iter: StoreIdIterator,

    year: Option<i32>,
    month: Option<u32>,
    day: Option<u32>,
}

impl Debug for DiaryEntryIterator {

    fn fmt(&self, fmt: &mut Formatter) -> RResult<(), FmtError> {
        write!(fmt, "DiaryEntryIterator<name = {}, year = {:?}, month = {:?}, day = {:?}>",
               self.name, self.year, self.month, self.day)
    }

}

impl DiaryEntryIterator {

    pub fn new(diaryname: String, iter: StoreIdIterator) -> DiaryEntryIterator {
        DiaryEntryIterator {
            name: diaryname,
            iter,

            year: None,
            month: None,
            day: None,
        }
    }

    // Filter by year, get all diary entries for this year
    pub fn year(mut self, year: i32) -> DiaryEntryIterator {
        self.year = Some(year);
        self
    }

    // Filter by month, get all diary entries for this month (every year)
    pub fn month(mut self, month: u32) -> DiaryEntryIterator {
        self.month = Some(month);
        self
    }

    // Filter by day, get all diary entries for this day (every year, every year)
    pub fn day(mut self, day: u32) -> DiaryEntryIterator {
        self.day = Some(day);
        self
    }

}

impl Filter<StoreId> for DiaryEntryIterator {
    fn filter(&self, id: &StoreId) -> bool {
        if id.is_in_diary(&self.name) {
            match (self.year, self.month, self.day) {
                (None    , None    , None)    => true,
                (Some(y) , None    , None)    => id.is_in_collection(&[&self.name, &y.to_string()]),
                (Some(y) , Some(m) , None)    => id.is_in_collection(&[&self.name, &y.to_string(), &m.to_string()]),
                (Some(y) , Some(m) , Some(d)) => id.is_in_collection(&[&self.name, &y.to_string(), &m.to_string(), &d.to_string()]),
                (None    , Some(_) , Some(_)) => false /* invalid case */,
                (None    , None    , Some(_)) => false /* invalid case */,
                (None    , Some(_) , None)    => false /* invalid case */,
                (Some(_) , None    , Some(_)) => false /* invalid case */,
            }
        } else {
            false
        }
    }
}

impl Iterator for DiaryEntryIterator {
    type Item = Result<StoreId>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            match self.iter.next() {
                None         => return None,
                Some(Err(e)) => return Some(Err(e)),
                Some(Ok(s))  => {
                    debug!("Next element: {:?}", s);
                    if Filter::filter(self, &s) {
                        return Some(Ok(s))
                    } else {
                        continue
                    }
                },
            }
        }
    }
}


/// Get diary names.
///
/// # Warning
///
/// Does _not_ run a `unique` on the iterator!
pub struct DiaryNameIterator(StoreIdIterator);

impl DiaryNameIterator {
    pub fn new(s: StoreIdIterator) -> DiaryNameIterator {
        DiaryNameIterator(s)
    }
}

impl Iterator for DiaryNameIterator {
    type Item = Result<String>;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(next) = self.0.next() {
            match next {
                Err(e) => return Some(Err(e)),
                Ok(next) => if next.is_in_collection(&["diary"]) {
                    return Some(next
                        .to_str()
                        .and_then(|s| {
                            s.split("diary/")
                                .nth(1)
                                .and_then(|n| n.split('/').next().map(String::from))
                                .ok_or_else(|| anyhow!("Error finding diary name"))
                        }));
                },
            }
        }

        None
    }

}