use std::env;
use std::fs;
use std::io::{self, BufReader, BufRead};
use itertools::Itertools;
use timelogging::timetracking::{nearest, process_input_file, generate_individual_timecards};

fn main() {
    // Process the file (stdin or file argument)
    let input = env::args().nth(1);
    let mut reader: Box<dyn BufRead> = match input {
        None => Box::new(BufReader::new(io::stdin())),
        Some(filename) => Box::new(BufReader::new(fs::File::open(filename).unwrap()))
    };

    // For each line of input (build internal data structures)
    let (mut start, mut finish, _) = process_input_file(&mut reader);


    // generate individual timecards
    let (ind, gtoth) = generate_individual_timecards(&mut start, &mut finish);

    // print the output
    for (act, duration) in ind.iter().sorted_by_key(|x| x.0) {
        let f: f64 = nearest(*duration as f64/3600.00);
        let mut fhrs: String = format!("{:2}hrs", 0.08);
        if f > 0.0 {
            fhrs = format!("{:.2}hrs", f);
        };
        println!("{}", format!("{:<75}{:>10}", act.to_string(), fhrs.to_string()));
    };

    println!();

    let gtotm: f64 = nearest((gtoth * 60.00) as f64);
    println!("{}", format!("Grand total: {:.2}hrs ({:.0} minutes)", gtoth, gtotm));
}
