use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::app::{App, AppResult};

/// Handles the key events and updates the state of [`App`].
pub fn handle_key_events(key_event: KeyEvent, app: &mut App) -> AppResult<()> {
    match key_event.code {
        // Exit application on `ESC` or `q`
        KeyCode::Esc | KeyCode::Char('q') => {
            app.quit();
        }
        // Exit application on `Ctrl-C`
        KeyCode::Char('c') | KeyCode::Char('C') => {
            if key_event.modifiers == KeyModifiers::CONTROL {
                app.quit();
            }
        }
        // Ditto operations
        KeyCode::Char('s') | KeyCode::Char('S') => app.toggle_sync(),
        KeyCode::Char('b') | KeyCode::Char('B') => app.toggle_cloud(),
        KeyCode::Char('p') | KeyCode::Char('P') => app.toggle_p2p(),
        // Car operation
        KeyCode::Char('a') | KeyCode::Char('A') => app.add_car(),
        KeyCode::Char('d') | KeyCode::Char('D') => app.remove_car(),
        // Car selector
        KeyCode::Up => match app.tabs.index {
            0 => app.select_previous_car(),
            1 => app.select_previous_peer(),
            _ => (),
        },
        KeyCode::Down => match app.tabs.index {
            0 => app.select_next_car(),
            1 => app.select_next_peer(),
            _ => (),
        },
        // Other handlers you could add here.
        KeyCode::Tab => {
            app.tabs.next();
        }
        _ => {}
    }
    Ok(())
}
