package ocelot.desktop.ui.event.handlers

import ocelot.desktop.geometry.Vector2D
import ocelot.desktop.ui.UiHandler
import ocelot.desktop.ui.event.{ClickEvent, MouseEvent}
import ocelot.desktop.ui.widget.Widget

import scala.collection.mutable

trait ClickHandler extends Widget {
  private val startPositions = new mutable.HashMap[MouseEvent.Button.Value, Vector2D]()
  private val Tolerance = 8

  eventHandlers += {
    case MouseEvent(MouseEvent.State.Press, button) =>
      startPositions += (button -> UiHandler.mousePosition)

    case MouseEvent(MouseEvent.State.Release, button) =>
      val mousePos = UiHandler.mousePosition

      if (startPositions.get(button).exists(p => (p - mousePos).lengthSquared < Tolerance * Tolerance)) {
        handleEvent(ClickEvent(button, mousePos))
      }

      startPositions.remove(button)
  }
}
