use libimagstore::store::Entry;
use libimagstore::store::Store;
use libimagentrylink::internal::InternalLinker;
use libimagnotes::note::Note;
use libimagnotes::note::NoteIterator;
use libimagstore::storeid::StoreIdIterator;
use result::Result;
use error::AnnotationErrorKind as AEK;
use error::MapErrInto;
use self::iter::*;
pub trait AnnotationFetcher<'a> {
fn all_annotations(&'a self) -> Result<AnnotationIter<'a>>;
fn annotations_for_entry(&'a self, entry: &Entry) -> Result<AnnotationIter<'a>>;
}
impl<'a> AnnotationFetcher<'a> for Store {
fn all_annotations(&'a self) -> Result<AnnotationIter<'a>> {
Note::all_notes(self)
.map(|iter| AnnotationIter::new(iter))
.map_err_into(AEK::StoreReadError)
}
fn annotations_for_entry(&'a self, entry: &Entry) -> Result<AnnotationIter<'a>> {
entry.get_internal_links()
.map_err_into(AEK::StoreReadError)
.map(|iter| StoreIdIterator::new(Box::new(iter.map(|e| e.get_store_id().clone()))))
.map(|iter| NoteIterator::new(self, iter))
.map(|iter| AnnotationIter::new(iter))
}
}
pub mod iter {
use toml::Value;
use libimagstore::toml_ext::TomlValueExt;
use libimagerror::into::IntoError;
use libimagnotes::note::Note;
use libimagnotes::note::NoteIterator;
use result::Result;
use error::AnnotationErrorKind as AEK;
use error::MapErrInto;
#[derive(Debug)]
pub struct AnnotationIter<'a>(NoteIterator<'a>);
impl<'a> AnnotationIter<'a> {
pub fn new(noteiter: NoteIterator<'a>) -> AnnotationIter<'a> {
AnnotationIter(noteiter)
}
}
impl<'a> Iterator for AnnotationIter<'a> {
type Item = Result<Note<'a>>;
fn next(&mut self) -> Option<Result<Note<'a>>> {
loop {
match self.0.next() {
Some(Ok(note)) => {
let hdr = note.get_header().read("annotation.is_annotation");
match hdr {
Ok(None) => continue, Ok(Some(Value::Boolean(true))) => return Some(Ok(note)),
Ok(Some(_)) => return Some(Err(AEK::HeaderTypeError.into_error())),
Err(e) => return Some(Err(e).map_err_into(AEK::HeaderReadError)),
}
},
Some(Err(e)) => return Some(Err(e).map_err_into(AEK::StoreReadError)),
None => return None, }
}
}
}
}