summaryrefslogtreecommitdiffstats
path: root/lib/domain/libimagnotes/src/note.rs
blob: 599a0db644130b7b3bee83e37805311db3b010ce (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
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
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 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::collections::BTreeMap;
use std::ops::Deref;

use toml::Value;

use libimagrt::runtime::Runtime;
use libimagentryedit::edit::Edit;
use libimagentryedit::error::Result as EditResult;
use libimagstore::storeid::IntoStoreId;
use libimagstore::storeid::StoreId;
use libimagstore::storeid::StoreIdIterator;
use libimagstore::store::FileLockEntry;
use libimagstore::store::Store;

use toml_query::read::TomlValueReadExt;
use toml_query::set::TomlValueSetExt;

use module_path::ModuleEntryPath;
use error::Result;
use error::NoteErrorKind as NEK;
use error::NoteError as NE;
use error::ResultExt;

#[derive(Debug)]
pub struct Note<'a> {
    entry: FileLockEntry<'a>,
}

impl<'a> Note<'a> {

    pub fn new(store: &Store, name: String, text: String) -> Result<Note> {
        use std::ops::DerefMut;

        debug!("Creating new Note: '{}'", name);
        let fle = {
            let mut lockentry = try!(ModuleEntryPath::new(name.clone())
                .into_storeid()
                .and_then(|id| store.create(id))
                .chain_err(|| NEK::StoreWriteError));

            {
                let entry  = lockentry.deref_mut();

                {
                    let header = entry.get_header_mut();
                    let _ = header
                        .set("note", Value::Table(BTreeMap::new()))
                        .chain_err(|| NEK::StoreWriteError);

                    let _ = header
                        .set("note.name", Value::String(name))
                        .chain_err(|| NEK::StoreWriteError);
                }

                *entry.get_content_mut() = text;
            }

            lockentry
        };

        Ok(Note { entry: fle })
    }

    pub fn set_name(&mut self, n: String) -> Result<()> {
        self.entry
            .get_header_mut()
            .set("note.name", Value::String(n))
            .chain_err(|| NEK::StoreWriteError)
            .map(|_| ())
    }

    pub fn get_name(&self) -> Result<String> {
        let header = self.entry.get_header();
        match header.read("note.name") {
            Ok(Some(&Value::String(ref s))) => Ok(s.clone()),
            Ok(_) => {
                Err(NE::from_kind(NEK::HeaderTypeError)).chain_err(|| NEK::StoreReadError)
            },
            Err(e) => Err(e).chain_err(|| NEK::StoreReadError)
        }
    }

    pub fn set_text(&mut self, n: String) {
        *self.entry.get_content_mut() = n
    }

    pub fn get_text(&self) -> &String {
        self.entry.get_content()
    }

    pub fn delete(store: &Store, name: String) -> Result<()> {
        ModuleEntryPath::new(name)
            .into_storeid()
            .and_then(|id| store.delete(id))
            .chain_err(|| NEK::StoreWriteError)
    }

    pub fn retrieve(store: &Store, name: String) -> Result<Note> {
        ModuleEntryPath::new(name)
            .into_storeid()
            .and_then(|id| store.retrieve(id))
            .chain_err(|| NEK::StoreWriteError)
            .map(|entry| Note { entry: entry })
    }

    pub fn get(store: &Store, name: String) -> Result<Option<Note>> {
        ModuleEntryPath::new(name)
            .into_storeid()
            .and_then(|id| store.get(id))
            .chain_err(|| NEK::StoreWriteError)
            .map(|o| o.map(|entry| Note { entry: entry }))
    }

    pub fn all_notes(store: &Store) -> Result<NoteIterator> {
        store.retrieve_for_module("notes")
            .map(|iter| NoteIterator::new(store, iter))
            .chain_err(|| NEK::StoreReadError)
    }

}

impl<'a> Edit for Note<'a> {

    fn edit_content(&mut self, rt: &Runtime) -> EditResult<()> {
        self.entry.edit_content(rt)
    }

}

trait FromStoreId {
    fn from_storeid(&Store, StoreId) -> Result<Note>;
}

impl<'a> FromStoreId for Note<'a> {

    fn from_storeid(store: &Store, id: StoreId) -> Result<Note> {
        debug!("Loading note from storeid: '{:?}'", id);
        match store.retrieve(id) {
            Err(e)    => Err(e).chain_err(|| NEK::StoreReadError),
            Ok(entry) => Ok(Note { entry: entry }),
        }
    }

}

impl<'a> Deref for Note<'a> {

    type Target = FileLockEntry<'a>;

    fn deref(&self) -> &FileLockEntry<'a> {
        &self.entry
    }

}

#[derive(Debug)]
pub struct NoteIterator<'a> {
    store: &'a Store,
    iditer: StoreIdIterator,
}

impl<'a> NoteIterator<'a> {

    pub fn new(store: &'a Store, iditer: StoreIdIterator) -> NoteIterator<'a> {
        NoteIterator {
            store: store,
            iditer: iditer,
        }
    }

}

impl<'a> Iterator for NoteIterator<'a> {
    type Item = Result<Note<'a>>;

    fn next(&mut self) -> Option<Result<Note<'a>>> {
        self.iditer
            .next()
            .map(|id| Note::from_storeid(self.store, id))
    }

}