package ocelot.desktop.ui.event.sources

import ocelot.desktop.ui.event.{MouseEvent, ScrollEvent}
import org.lwjgl.input.Mouse

import scala.collection.mutable

object MouseEvents {
  private val _events = new mutable.ArrayBuffer[MouseEvent]
  private val _pressedButtons = new mutable.HashSet[MouseEvent.Button.Value]()

  def events: Iterator[MouseEvent] = _events.iterator

  def pressedButtons: Iterator[MouseEvent.Button.Value] = _pressedButtons.iterator

  def init(): Unit = {
    Mouse.create()
  }

  def update(): Unit = {
    ScrollEvents._events.clear()
    _events.clear()
    while (Mouse.next()) {
      val buttonIdx = Mouse.getEventButton

      if (MouseEvent.Button.values.map(_.id).contains(buttonIdx)) {
        val button = MouseEvent.Button(buttonIdx)
        val state = if (Mouse.getEventButtonState) MouseEvent.State.Pressed else MouseEvent.State.Released
        _pressedButtons(button) = Mouse.getEventButtonState
        _events += MouseEvent(state, button)
      }

      val delta = Mouse.getEventDWheel
      if (delta != 0)
        ScrollEvents._events += ScrollEvent(delta.sign)
    }
  }

  def destroy(): Unit = {
    Mouse.destroy()
  }

  def isDown(button: MouseEvent.Button.Value): Boolean = pressedButtons.contains(button)

  def releaseButtons(): Unit = {
    for (button <- pressedButtons) {
      _events += MouseEvent(MouseEvent.State.Released, button)
    }

    _pressedButtons.clear()
  }
}
