use debounce::EventDebouncer;
use getopts::Options;
use std::env;
use std::error::Error;
use std::io::{self, Write};
use std::time::Duration;

fn main() -> Result<(), Box<dyn Error>> {
    // Parse arguments
    let args: Vec<String> = env::args().collect();
    let mut opts = Options::new();
    opts.reqopt("d", "", "debounce delay in milliseconds", "TIMEOUT");
    let matches = opts.parse(&args[1..])?;
    let delay = matches.opt_str("d").unwrap().parse()?;

    // Create threaded debouncer
    let debouncer = EventDebouncer::new(Duration::from_millis(delay), move |data: String| {
        // Debounced strings are written to stdout
        io::stdout().write_all(data.as_bytes()).ok();
    });

    // Send strings from stdin to the debouncer indefinitely
    loop {
        let mut buffer = String::new();
        let stdin = io::stdin();
        stdin.read_line(&mut buffer)?;
        debouncer.put(buffer);
    }
}