use clap::ArgMatches;
use chrono::naive::NaiveDate;
use chrono::naive::NaiveDateTime;
use failure::Error;
use failure::Fallible as Result;
use failure::err_msg;
use libimagrt::runtime::Runtime;
use libimagtimetrack::tag::TimeTrackingTag;
use libimagtimetrack::store::TimeTrackStore;
const DATE_TIME_PARSE_FMT : &str = "%Y-%m-%dT%H:%M:%S";
const DATE_PARSE_FMT : &str = "%Y-%m-%d";
pub fn track(rt: &Runtime) -> Result<()> {
let (_, cmd) = rt.cli().subcommand();
let cmd = cmd.unwrap();
fn get_time(cmd: &ArgMatches, clap_name: &str) -> Result<Option<NaiveDateTime>> {
match cmd.value_of(clap_name) {
None => bail!("Not specified in commandline: {}", clap_name),
Some("now") => Ok(Some(::chrono::offset::Local::now().naive_local())),
Some(els) => match NaiveDateTime::parse_from_str(els, DATE_TIME_PARSE_FMT) {
Ok(ndt) => Ok(Some(ndt)),
Err(_) => Ok(Some(NaiveDate::parse_from_str(els, DATE_PARSE_FMT)?.and_hms(0, 0, 0))),
}
}
}
let start = get_time(&cmd, "start-time")?.ok_or_else(|| err_msg("No start-time"))?;
let stop = get_time(&cmd, "end-time")?.ok_or_else(|| err_msg("No end-time"))?;
cmd.values_of("tags")
.unwrap() .map(String::from)
.map(TimeTrackingTag::from)
.map(|ttt| {
let entry = rt.store().create_timetracking(&start, &stop, &ttt)?;
rt.report_touched(entry.get_location()).map_err(Error::from)
})
.collect::<Result<Vec<_>>>()
.map(|_| ())
}