//! This module provides a few structs to wrap common input struts to a rusty interface
//!
//! Types like:
//! - `KEY_EVENT_RECORD`
//! - `MOUSE_EVENT_RECORD`
//! - `ControlKeyState`
//! - `ButtonState`
//! - `EventFlags`
//! - `InputEventType`
//! - `INPUT_RECORD`

use winapi::shared::minwindef::{DWORD, WORD};
use winapi::um::wincon::{
    INPUT_RECORD_Event, KEY_EVENT_RECORD_uChar, FOCUS_EVENT, INPUT_RECORD, KEY_EVENT,
    KEY_EVENT_RECORD, MENU_EVENT, MOUSE_EVENT, MOUSE_EVENT_RECORD, WINDOW_BUFFER_SIZE_EVENT,
};

use super::coord::Coord;

/// Describes a keyboard input event in a console INPUT_RECORD structure.
/// link: [https://docs.microsoft.com/en-us/windows/console/key-event-record-str]
pub struct KeyEventRecord {
    /// If the key is pressed, this member is TRUE. Otherwise, this member is FALSE (the key is released).
    pub key_down: bool,
    /// The repeat count, which indicates that a key is being held down.
    /// For example, when a key is held down, you might get five events with this member equal to 1, one event with this member equal to 5, or multiple events with this member greater than or equal to 1.
    pub repeat_count: u16,
    /// A virtual-key code that identifies the given key in a device-independent manner.
    pub virtual_key_code: WORD,
    /// The virtual scan code of the given key that represents the device-dependent value generated by the keyboard hardware.
    pub virtual_scan_code: u16,
    /// A union of the following members.
    ///
    /// - UnicodeChar
    ///   Translated Unicode character.
    ///
    /// - AsciiChar
    ///  Translated ASCII character.
    /// TODO, make this a rust type.
    pub u_char: KEY_EVENT_RECORD_uChar,
    /// The state of the control keys.
    pub control_key_state: ControlKeyState,
}

impl KeyEventRecord {}

impl From<KEY_EVENT_RECORD> for KeyEventRecord {
    fn from(event: KEY_EVENT_RECORD) -> Self {
        KeyEventRecord {
            key_down: event.bKeyDown == 1,
            repeat_count: event.wRepeatCount,
            virtual_key_code: event.wVirtualKeyCode,
            virtual_scan_code: event.wVirtualScanCode,
            u_char: event.uChar,
            control_key_state: ControlKeyState(event.dwControlKeyState),
        }
    }
}

#[derive(PartialOrd, PartialEq, Debug, Copy, Clone)]
pub struct MouseEvent {
    pub mouse_position: Coord,
    pub button_state: ButtonState,
    pub control_key_state: ControlKeyState,
    pub event_flags: EventFlags,
}

impl From<MOUSE_EVENT_RECORD> for MouseEvent {
    fn from(event: MOUSE_EVENT_RECORD) -> Self {
        MouseEvent {
            mouse_position: Coord::from(event.dwMousePosition),
            button_state: ButtonState::from(event.dwButtonState),
            control_key_state: ControlKeyState(event.dwControlKeyState),
            event_flags: EventFlags::from(event.dwEventFlags),
        }
    }
}

/// The status of the mouse buttons.
/// The least significant bit corresponds to the leftmost mouse button.
/// The next least significant bit corresponds to the rightmost mouse button.
/// The next bit indicates the next-to-leftmost mouse button.
/// The bits then correspond left to right to the mouse buttons.
/// A bit is 1 if the button was pressed.
///
/// [Ms Docs](https://docs.microsoft.com/en-us/windows/console/mouse-event-record-str#members)
#[derive(PartialOrd, PartialEq, Debug, Copy, Clone)]
pub enum ButtonState {
    Release = 0x0000,
    /// The leftmost mouse button.
    FromLeft1stButtonPressed = 0x0001,
    /// The second button from the left.
    FromLeft2ndButtonPressed = 0x0004,
    /// The third button from the left.
    FromLeft3rdButtonPressed = 0x0008,
    /// The fourth button from the left.
    FromLeft4thButtonPressed = 0x0010,
    /// The rightmost mouse button.
    RightmostButtonPressed = 0x0002,
    /// This button state is not recognized.
    Unknown = 0x0021,
    /// The wheel was rotated backward, toward the user; this will only be activated for `MOUSE_WHEELED ` from `dwEventFlags`
    Negative = 0x0020,
}

impl From<DWORD> for ButtonState {
    fn from(event: DWORD) -> Self {
        let e = event as i32;

        match e {
            0x0000 => ButtonState::Release,
            0x0001 => ButtonState::FromLeft1stButtonPressed,
            0x0004 => ButtonState::FromLeft2ndButtonPressed,
            0x0008 => ButtonState::FromLeft3rdButtonPressed,
            0x0010 => ButtonState::FromLeft4thButtonPressed,
            0x0002 => ButtonState::RightmostButtonPressed,
            _ if e < 0 => ButtonState::Negative,
            _ => ButtonState::Unknown,
        }
    }
}

#[derive(PartialOrd, PartialEq, Debug, Copy, Clone)]
pub struct ControlKeyState(u32);

impl ControlKeyState {
    pub fn has_state(&self, state: u32) -> bool {
        (state & self.0) != 0
    }
}

/// The type of mouse event.
/// If this value is zero, it indicates a mouse button being pressed or released.
/// Otherwise, this member is one of the following values.
///
/// [Ms Docs](https://docs.microsoft.com/en-us/windows/console/mouse-event-record-str#members)
#[derive(PartialOrd, PartialEq, Debug, Copy, Clone)]
pub enum EventFlags {
    PressOrRelease = 0x0000,
    // The second click (button press) of a double-click occurred. The first click is returned as a regular button-press event.
    DoubleClick = 0x0002,
    // The horizontal mouse wheel was moved.
    MouseHwheeled = 0x0008,
    // If the high word of the dwButtonState member contains a positive value, the wheel was rotated to the right. Otherwise, the wheel was rotated to the left.
    MouseMoved = 0x0001,
    // A change in mouse position occurred.
    // The vertical mouse wheel was moved, if the high word of the dwButtonState member contains a positive value, the wheel was rotated forward, away from the user.
    // Otherwise, the wheel was rotated backward, toward the user.
    MouseWheeled = 0x0004,
}

impl From<DWORD> for EventFlags {
    fn from(event: DWORD) -> Self {
        match event {
            0x0000 => EventFlags::PressOrRelease,
            0x0002 => EventFlags::DoubleClick,
            0x0008 => EventFlags::MouseHwheeled,
            0x0001 => EventFlags::MouseMoved,
            0x0004 => EventFlags::MouseWheeled,
            _ => panic!("Event flag {} does not exist.", event),
        }
    }
}

/// Describes an input event in the console input buffer.
/// These records can be read from the input buffer by using the `ReadConsoleInput` or `PeekConsoleInput` function, or written to the input buffer by using the `WriteConsoleInput` function.
///
/// [Ms Docs](https://docs.microsoft.com/en-us/windows/console/input-record-str)
#[derive(Clone)]
pub struct InputRecord {
    /// A handle to the type of input event and the event record stored in the Event member.
    pub event_type: InputEventType,
    /// The event information. The format of this member depends on the event type specified by the EventType member.
    /// Todo: wrap with rust type.
    pub event: INPUT_RECORD_Event,
}

impl From<INPUT_RECORD> for InputRecord {
    fn from(event: INPUT_RECORD) -> Self {
        InputRecord {
            event_type: InputEventType::from(event.EventType),
            event: event.Event,
        }
    }
}

/// A handle to the type of input event and the event record stored in the Event member.
///
/// [Ms Docs](https://docs.microsoft.com/en-us/windows/console/input-record-str#members)
#[derive(PartialOrd, PartialEq, Debug, Copy, Clone)]
pub enum InputEventType {
    /// The Event member contains a `KEY_EVENT_RECORD` structure with information about a keyboard event.
    KeyEvent = KEY_EVENT as isize,
    /// The Event member contains a `MOUSE_EVENT_RECORD` structure with information about a mouse movement or button press event.
    MouseEvent = MOUSE_EVENT as isize,
    /// The Event member contains a `WINDOW_BUFFER_SIZE_RECORD` structure with information about the new size of the console screen buffer.
    WindowBufferSizeEvent = WINDOW_BUFFER_SIZE_EVENT as isize,
    /// The Event member contains a `FOCUS_EVENT_RECORD` structure. These events are used internally and should be ignored.
    FocusEvent = FOCUS_EVENT as isize,
    /// The Event member contains a `MENU_EVENT_RECORD` structure. These events are used internally and should be ignored.
    MenuEvent = MENU_EVENT as isize,
}

impl From<WORD> for InputEventType {
    fn from(event: WORD) -> Self {
        match event {
            KEY_EVENT => InputEventType::KeyEvent,
            MOUSE_EVENT => InputEventType::MouseEvent,
            WINDOW_BUFFER_SIZE_EVENT => InputEventType::WindowBufferSizeEvent,
            FOCUS_EVENT => InputEventType::FocusEvent,
            MENU_EVENT => InputEventType::MenuEvent,
            _ => panic!("Input event type {} does not exist.", event),
        }
    }
}
