///|
#derive(Debug, Eq)
pub(all) struct KeyboardEvent {
  window_id : UInt32
  keyboard_id : UInt32
  scancode : Int32
  keycode : UInt32
  modifiers : UInt32
  repeat : Bool
}

///|
pub extend KeyboardEvent with Debug::{to_repr}

///|
pub extend KeyboardEvent with Eq::{not_equal, equal}

///|
#derive(Debug, Eq)
pub(all) struct MouseMotionEvent {
  window_id : UInt32
  mouse_id : UInt32
  state : UInt32
  x : Float
  y : Float
  xrel : Float
  yrel : Float
}

///|
pub extend MouseMotionEvent with Debug::{to_repr}

///|
pub extend MouseMotionEvent with Eq::{not_equal, equal}

///|
#derive(Debug, Eq)
pub(all) struct MouseButtonEvent {
  window_id : UInt32
  mouse_id : UInt32
  button : Byte
  clicks : Byte
  x : Float
  y : Float
}

///|
pub extend MouseButtonEvent with Debug::{to_repr}

///|
pub extend MouseButtonEvent with Eq::{not_equal, equal}

///|
#derive(Debug, Eq)
pub(all) struct WindowEvent {
  window_id : UInt32
  name : WindowEventName
  size : Size?
}

///|
pub extend WindowEvent with Debug::{to_repr}

///|
pub extend WindowEvent with Eq::{not_equal, equal}

///|
#derive(Debug, Eq)
pub(all) struct TextInputEvent {
  text : String
}

///|
pub extend TextInputEvent with Debug::{to_repr}

///|
pub extend TextInputEvent with Eq::{not_equal, equal}

///|
#derive(Debug, Eq)
pub(all) enum WindowEventName {
  Exposed
  Resized
  PixelSizeChanged
  DisplayScaleChanged
  CloseRequested
}

///|
pub extend WindowEventName with Debug::{to_repr}

///|
pub extend WindowEventName with Eq::{not_equal, equal}

///|
#derive(Debug, Eq)
pub(all) enum Event {
  Quit
  KeyDown(KeyboardEvent)
  KeyUp(KeyboardEvent)
  MouseMotion(MouseMotionEvent)
  MouseButtonDown(MouseButtonEvent)
  MouseButtonUp(MouseButtonEvent)
  TextInput(TextInputEvent)
  WindowExposed(WindowEvent)
  WindowResized(WindowEvent)
  WindowPixelSizeChanged(WindowEvent)
  WindowDisplayScaleChanged(WindowEvent)
  WindowCloseRequested(WindowEvent)
  Other(UInt32)
}

///|
pub extend Event with Debug::{to_repr}

///|
pub extend Event with Eq::{not_equal, equal}

///|
struct EventListener {
  raw : @sys.EventWatch
}

///|
let call_event_watch_callback : FuncRef[((Bytes) -> Unit, Bytes) -> Unit] = fn(
  callback,
  event,
) {
  callback(event)
}

///|
pub fn poll_event() -> Event? {
  let raw = @sys.Event()
  if @sys.poll_event(raw) {
    Some(Event::from_raw(raw))
  } else {
    None
  }
}

///|
fn wait_event_timeout(timeout_ms : Int32) -> Event? {
  let raw = @sys.Event()
  if @sys.wait_event_timeout(raw, timeout_ms) {
    Some(Event::from_raw(raw))
  } else {
    None
  }
}

///|
fn Event::from_raw(raw : @sys.Event) -> Event {
  let event_type = raw.event_type()
  match event_type {
    @sys.EVENT_QUIT => Quit
    @sys.EVENT_KEY_DOWN => KeyDown(KeyboardEvent::from_raw(raw))
    @sys.EVENT_KEY_UP => KeyUp(KeyboardEvent::from_raw(raw))
    @sys.EVENT_MOUSE_MOTION => MouseMotion(MouseMotionEvent::from_raw(raw))
    @sys.EVENT_MOUSE_BUTTON_DOWN =>
      MouseButtonDown(MouseButtonEvent::from_raw(raw))
    @sys.EVENT_MOUSE_BUTTON_UP => MouseButtonUp(MouseButtonEvent::from_raw(raw))
    @sys.EVENT_TEXT_INPUT => TextInput(TextInputEvent::from_raw(raw))
    @sys.EVENT_WINDOW_EXPOSED =>
      WindowExposed(WindowEvent::from_raw(raw, Exposed))
    @sys.EVENT_WINDOW_RESIZED =>
      WindowResized(WindowEvent::from_raw(raw, Resized))
    @sys.EVENT_WINDOW_PIXEL_SIZE_CHANGED =>
      WindowPixelSizeChanged(WindowEvent::from_raw(raw, PixelSizeChanged))
    @sys.EVENT_WINDOW_DISPLAY_SCALE_CHANGED =>
      WindowDisplayScaleChanged(WindowEvent::from_raw(raw, DisplayScaleChanged))
    @sys.EVENT_WINDOW_CLOSE_REQUESTED =>
      WindowCloseRequested(WindowEvent::from_raw(raw, CloseRequested))
    _ => Other(event_type)
  }
}

///|
fn KeyboardEvent::from_raw(raw : @sys.Event) -> KeyboardEvent {
  let key = raw.key()
  {
    window_id: key.window_id(),
    keyboard_id: key.which(),
    scancode: key.scancode(),
    keycode: key.key(),
    modifiers: key.mod(),
    repeat: key.repeat(),
  }
}

///|
fn MouseMotionEvent::from_raw(raw : @sys.Event) -> MouseMotionEvent {
  let motion = raw.motion()
  {
    window_id: motion.window_id(),
    mouse_id: motion.which(),
    state: motion.state(),
    x: motion.x(),
    y: motion.y(),
    xrel: motion.xrel(),
    yrel: motion.yrel(),
  }
}

///|
fn MouseButtonEvent::from_raw(raw : @sys.Event) -> MouseButtonEvent {
  let button = raw.button()
  {
    window_id: button.window_id(),
    mouse_id: button.which(),
    button: button.button(),
    clicks: button.clicks(),
    x: button.x(),
    y: button.y(),
  }
}

///|
fn WindowEvent::from_raw(
  raw : @sys.Event,
  name : WindowEventName,
) -> WindowEvent {
  let window = raw.window()
  let size = match name {
    Resized | PixelSizeChanged =>
      Some(Size::{ width: window.data1(), height: window.data2(), })
    Exposed | DisplayScaleChanged | CloseRequested => None
  }
  { window_id: window.window_id(), name, size, }
}

///|
fn TextInputEvent::from_raw(raw : @sys.Event) -> TextInputEvent {
  let text = raw.text()
  { text: @utf8.decode_lossy(text.text()), }
}

///|
fn WindowEventName::matches(
  self : Self,
  event : Event,
  window_id : UInt32,
) -> WindowEvent? {
  let window_event = match event {
    WindowExposed(event) if self == Exposed => Some(event)
    WindowResized(event) if self == Resized => Some(event)
    WindowPixelSizeChanged(event) if self == PixelSizeChanged => Some(event)
    WindowDisplayScaleChanged(event) if self == DisplayScaleChanged =>
      Some(event)
    WindowCloseRequested(event) if self == CloseRequested => Some(event)
    _ => None
  }
  match window_event {
    Some(event) if event.window_id == window_id => Some(event)
    _ => None
  }
}

///|
/// Dispose on the main thread before SDL shutdown. Queued callbacks are cancelled.
/// Repeated disposal is harmless, including from the listener's own callback.
pub fn EventListener::dispose(self : Self) -> Unit {
  @sys.remove_event_watch(self.raw)
}

///|
/// Register after SDL initialization on the main thread. Events raised there run
/// synchronously; events raised on other threads run during main-thread pumping.
pub fn add_event_watch(
  callback : (Event) -> Unit,
) -> EventListener raise SdlError {
  let raw_callback = fn(raw_event) {
    callback(Event::from_raw(@sys.Event::from_bytes(raw_event)))
  }
  let raw = @sys.add_event_watch(call_event_watch_callback, raw_callback)
  if raw.is_null() {
    raise_last_error("SDL_AddEventWatch")
  }
  { raw, }
}

///|
/// Observe this window on the main thread. Synchronous expose/resize callbacks
/// also run during the platform's modal resize loop.
pub fn Window::on(
  self : Self,
  name : WindowEventName,
  callback : (WindowEvent) -> Unit,
) -> EventListener raise SdlError {
  let window_id = self.id()
  add_event_watch(fn(event) {
    if name.matches(event, window_id) is Some(window_event) {
      callback(window_event)
    }
  })
}

///|
pub fn delay(milliseconds : UInt32) -> Unit {
  @sys.delay(milliseconds)
}