use std::io::Write;
use failure::Fallible as Result;
use failure::err_msg;
use failure::Error;
use resiter::AndThen;
use libimagdiary::diary::Diary;
use libimagrt::runtime::Runtime;
use libimagdiary::diaryid::DiaryId;
use libimagdiary::diaryid::FromStoreId;
use libimagstore::storeid::IntoStoreId;
use crate::util::get_diary_name;
pub fn list(rt: &Runtime) -> Result<()> {
let diaryname = get_diary_name(rt)
.ok_or_else(|| err_msg("No diary selected. Use either the configuration file or the commandline option"))?;
let mut ids = Diary::entries(rt.store(), &diaryname)?
.and_then_ok(|id| DiaryId::from_storeid(&id))
.collect::<Result<Vec<_>>>()?;
ids.sort_by_key(|id| {
[id.year() as u32, id.month(), id.day(), id.hour(), id.minute(), id.second()]
});
ids.into_iter()
.map(IntoStoreId::into_storeid)
.and_then_ok(|id| {
rt.report_touched(&id)?;
if !rt.output_is_pipe() {
writeln!(rt.stdout(), "{}", id).map_err(Error::from)
} else {
Ok(())
}
})
.collect()
}