// File: src/input.rs
// Author: Hadi Cahyadi <cumulus13@gmail.com>

use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use std::time::Duration;

/// Decoded user action.
#[derive(Debug, Clone, PartialEq)]
pub enum Action {
    SelectNext,
    SelectPrev,
    VolumeUp,
    VolumeDown,
    ToggleMute,
    Quit,
    None,
}

/// Poll for a key event with a timeout. Returns `Action::None` if no key arrived.
pub fn poll_action(timeout: Duration) -> Action {
    if event::poll(timeout).unwrap_or(false) {
        if let Ok(Event::Key(KeyEvent {
            code,
            modifiers,
            kind,
            ..
        })) = event::read()
        {
            // On Windows crossterm fires both Press and Release for every key.
            // Ignore Release (and Repeat) so one physical keypress = one action.
            if kind != KeyEventKind::Press {
                return Action::None;
            }
            return match (code, modifiers) {
                (KeyCode::Char('q') | KeyCode::Char('Q') | KeyCode::Esc, _) => Action::Quit,
                (KeyCode::Char('c'), KeyModifiers::CONTROL) => Action::Quit,
                (KeyCode::Char('m') | KeyCode::Char('M'), _) => Action::ToggleMute,
                (KeyCode::Right | KeyCode::Tab, _) => Action::SelectNext,
                (KeyCode::Left, _) => Action::SelectPrev,
                (KeyCode::Up, _) => Action::VolumeUp,
                (KeyCode::Down, _) => Action::VolumeDown,
                (KeyCode::F(6), _) => Action::SelectNext,
                _ => Action::None,
            };
        }
    }
    Action::None
}
