#[cfg(all(feature = "socketcan", feature = "tui"))]
fn main() -> Result<(), Box<dyn std::error::Error>> {
    use std::time::Duration;

    use crossterm::event::{Event, KeyCode};
    use kcan::{CanMonitor, SocketCanBus, TuiCanMonitor};
    use scrin::{Terminal, TerminalOptions};

    let interface = std::env::args().nth(1).unwrap_or_else(|| "can0".to_owned());
    let mut bus = SocketCanBus::open(&interface)?;
    let mut monitor = TuiCanMonitor::new(CanMonitor::new(512));
    let mut terminal = Terminal::init_with(TerminalOptions::new())?;

    loop {
        monitor.poll_available(&mut bus, Duration::from_millis(25), 64)?;
        monitor.advance_tick();
        terminal.draw(|frame| monitor.render_frame(frame))?;

        if let Some(event) = terminal.poll_event()? {
            if let Event::Key(key) = event {
                let ch = match key.code {
                    KeyCode::Char(ch) => Some(ch),
                    KeyCode::Esc => Some('q'),
                    _ => None,
                };

                if let Some(command) = ch.and_then(kcan::CanMonitorCommand::from_key) {
                    if monitor.apply_command(command) {
                        break;
                    }
                }
            }
        }
    }

    terminal.restore()?;
    Ok(())
}

#[cfg(not(all(feature = "socketcan", feature = "tui")))]
fn main() {
    eprintln!("enable the `socketcan` and `tui` features to run this example");
}
